/* file: fork_exec.c Illustrates the use of exec() with fork(), and environ. Also illustrates separate compilation and linking separately compiled code with main program. To compile this program: gcc -c print_child_status.c gcc -o fork_exec print_child_status.o fork_exec.c */ #define _XOPEN_SOURCE 500 #include #include #include #include #include #include #include #include #include #include #define SLEEP_TIME 1 extern char ** environ; /* see "man environ" for explanation */ extern void print_child_status (int status); int main(int argc, char *argv[]) { pid_t child; int status; char *argument_list[] = {"child", NULL}; int i; if (argc !=1) { fprintf (stderr, "This program does not accept command-line arguments\n"); exit (-1); } for (i = 0; environ[i]; i++) { fprintf (stdout, "environ[%d] = \"%s\"\n", i, environ[i]); } /* create a child process */ child = fork(); if (child == -1) { /* call to fork failed */ perror ("fork failed"); exit (-1); } if (child != 0) { fprintf (stdout, "This is the parent process, with own pid %d\n", getpid()); if (waitpid (child, &status, 0) == -1) { perror ("waitpid failed"); exit (-1); } print_child_status (status); } else { fprintf (stdout, "This is the child process, with own pid %d " "and parent pid %d\n", (int) getpid(), (int) getppid()); if (execve ("child", argument_list, environ) == -1) { perror ("execve failed"); } fprintf (stderr, "execution should never reach here"); } return 0; }