#include #include #include #include #include #include #include char* getoutput(char* command){ int pipefds[2]; pipe(pipefds); int read_end = pipefds[0]; int write_end = pipefds[1]; pid_t pid = fork(); if(pid){ // We're the parent process close(write_end); char* buffer = (char*)malloc(128); size_t allocation_size = 128; size_t actually_read = 0; size_t readlen = read(read_end, buffer, 128); actually_read += readlen; while(readlen > 0){ // read more out of the pipe! buffer = (char*)realloc(buffer, allocation_size + 128); allocation_size += 128; readlen = read(read_end, buffer+actually_read, 128); actually_read += readlen; } buffer[actually_read] = 0; wait(0); close(read_end); return buffer; } else { // We're the child process close(read_end); dup2(write_end, 1); execl("/bin/sh", "sh", "-c", command, 0); perror("exec"); close(write_end); } } int main(){ char* output = getoutput("uname"); printf("Output was: %s\n", output); char* other_output = getoutput("whoami"); printf("Output was: %s\n", other_output); printf("Original Output was: %s\n", output); free(output); free(other_output); char* long_test = getoutput("last"); printf("Last output was: "); puts(long_test); free(long_test); char* pipe_test = getoutput("ps axu | grep a.out"); printf("Pipe test output: %s\n", pipe_test); free(pipe_test); return 0; }