#include #include #include #include #include #include #include #include #include #include int pipe_ends[2]; int read_end; int write_end; void handle_signal(int signal){ char* message = "Caught the signal!\n"; write(2, message, strlen(message)); } void* run_system_in_other_thread(void* cmd){ system(cmd); // Into the pipe here kill(getpid(), 13); close(write_end); close(read_end); return 0; } char* getoutput(char* cmd){ pipe(pipe_ends); read_end = pipe_ends[0]; write_end = pipe_ends[1]; pid_t pid = fork(); if(pid == 0){ // We're the child dup2(write_end, 1); close(read_end); execl("/bin/sh", "sh", "-c", cmd, (char *) 0); printf("Command was probably wrong\n"); } // We must be the parent close(write_end); char *buffer = malloc(1024); size_t buffer_size = 1024; size_t totallen = 0; while(1){ size_t readlen = read(read_end, buffer + totallen, buffer_size - totallen); // Out of the pipe here totallen += readlen; if(readlen < 1) break; if(buffer_size - totallen == 0){ buffer = realloc(buffer, buffer_size + 1024); buffer_size += 1024; } } buffer[totallen] = 0; close(read_end); return buffer; // return "fish"; // ['f', 'i', 's', 'h', 0] } int main(){ struct sigaction handler; handler.sa_handler = handle_signal; sigaction(13, &handler, 0); // A char* is not the same as a char char a_letter = 'a'; char *text = getoutput("last"); // char *text = getoutput("cat /usr/share/dict/american-english"); printf("Size of char: %d\nSize of char*: %d\n", sizeof(a_letter), sizeof(text)); printf("Length of text: %d\n", strlen(text)); puts(text); printf("Address of text: %lx (%lu)\n", text, text); free(text); return 0; }