/* fork.c - demo of fork and exec */ #include #include main(int argc, char **argv) { char *newargv[3]; int i, j; extern int errno; newargv[0] = "cat"; newargv[1] = "f1"; newargv[2] = NULL; for (j = 1; j <= 4; ++j) { /* Print out Process ID. Used to prove we are running this loop * in our child process. ... Force output */ printf("I am %d. j = %d\n", getpid(), j); fflush(stdout); /* Try to fork and create a new process address space, then * in the child: attempt to exec the 'cat' program/command. */ if (fork() == 0) { printf (" process %d has just been born\n", getpid()); i = execv("/usr/bin/cat", newargv); printf (" pid = %d: execv returned %d ", getpid(), i); if (i == -1) printf (" errno = %d", errno); printf ("\n"); } else { /* The parent: if we successfully called cat, we are going to "wait" * until it finishes and then only move on from there. */ printf (" pid = %d: i = %d...", getpid(), i); printf ("wait returns %d...", wait(&i)); printf ("i = %d\n", getpid(), i); } } } /*------------------------ Example output ------------------------------ I am 24004. j = 1 process 24005 has just been born this is the file f1 pid = 24004: i = 0...wait returns 24005...i = 24004 I am 24004. j = 2 process 24006 has just been born this is the file f1 pid = 24004: i = 0...wait returns 24006...i = 24004 I am 24004. j = 3 process 24007 has just been born this is the file f1 pid = 24004: i = 0...wait returns 24007...i = 24004 I am 24004. j = 4 process 24008 has just been born this is the file f1 pid = 24004: i = 0...wait returns 24008...i = 24004 ------------------------------------------------------------------------*/