#include #include #include #include #include #define USE_FORK //#define USE_POPEN //#define USE_POSIX_SPAWN int some_var = 1; int main(int argc, char** argv, char** env) { int pfds[2]; int err; int pid; err = pipe(pfds); #ifdef USE_FORK pid = fork(); if (pid < 0) { perror("fork"); exit(EXIT_FAILURE); } else if (pid == 0) { // Child printf("Child: Some var: %d @ %p\n", some_var, &some_var); close(pfds[0]); close(STDOUT_FILENO); dup2(pfds[1], STDOUT_FILENO); some_var = 2; printf("Child: Some var: %d @ %p\n", some_var, &some_var); err = execv("/bin/date", argv); perror("exec"); exit(EXIT_FAILURE); } else { // Parent printf("Parent: Some var: %d @ %p\n", some_var, &some_var); close(pfds[1]); char buf[1024]; int wstatus; FILE* fp = fdopen(pfds[0], "r"); fgets(buf, sizeof(buf), fp); waitpid(pid, &wstatus, 0); printf("FORK: Date returned: \"%s\" and exited with code %d\n", buf, wstatus); printf("Parent: Some var: %d @ %p\n", some_var, &some_var); } #endif #ifdef USE_POPEN FILE* fp = popen("/bin/date", "r"); char buf[1024]; int wstatus; fgets(buf, sizeof(buf), fp); wstatus = pclose(fp); printf("POPEN: Date returned: \"%s\" and exited with code %d\n", buf, wstatus); #endif #ifdef USE_POSIX_SPAWN int wstatus; posix_spawn_file_actions_t actions; posix_spawn_file_actions_init(&actions); posix_spawn_file_actions_adddup2(&actions, pfds[1], STDOUT_FILENO); posix_spawn_file_actions_addclose(&actions, pfds[0]); posix_spawn(&pid, "/bin/date", &actions, NULL, argv, env); close(pfds[1]); char buf[1024]; FILE* fp = fdopen(pfds[0], "r"); fgets(buf, sizeof(buf), fp); waitpid(pid, &wstatus, 0); printf("POSIX: Date returned: \"%s\" and exited with code %d\n", buf, wstatus); #endif return 0; }