/* fork1.c - demo of fork and exec * Note that exec takes 2 parameters: name of binary; argument list */ #include #include main(int argc, char **argv) { char *catarg[3]; int i, j, return_value; /* Here are the arguments to pass to child process "cat f1.txt". */ catarg[0] = "cat"; catarg[1] = "f1.txt"; catarg[2] = NULL; for (j = 1; j <= 4; ++j) { /* Print out Process ID. Used to prove which process is talking. */ printf("I am process %d. Iteration %d\n", getpid(), j); /* 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 (" Child process %d has just been born\n", getpid()); i = execv("/bin/cat", catarg); printf (" (child) pid = %d: execv returned %d\n", getpid(), i); } else { /* The parent: if we successfully called cat, we are going to "wait" * until it finishes and then only move on from there. */ printf (" (parent) pid = %d: i = %d ", getpid(), i); return_value = wait(&i); printf ("wait returns %d ", return_value); printf ("wait changed i to %d\n\n", i); } } }