This section is mainly about process creation in UNIX systems.

The fork() System Call

We use fork() to create(clone) a new process.

Let’s call the following code p1

int main(int argc, char *argv[])
{
	printf("hello world (pid:%d)\\n", (int) getpid());
	    int rc = fork();
	    if (rc < 0) {         // fork failed; exit
	        fprintf(stderr, "fork failed\\n");
	        exit(1);
	    } else if (rc == 0) { // child (new process)
	        printf("hello, I am child (pid:%d)\\n", (int) getpid());
	    } else {              // parent goes down this path (main)
	        printf("hello, I am parent of %d (pid:%d)\\n",
	                rc, (int) getpid());
	}
	return 0;
}

And the code will have the following output

$ ./p1
	hello world (pid:29146)
	hello, I am parent of 29147 (pid:29146)
	hello, I am child (pid:29147)

The fork() will create a process that is an almost exact copy of the calling process.

So once the fork() is called, the OS now is looking at two copies of the program p1 running, and both are about to return from the fork() sytem call. The newly-created process won’t start running at main() , but will start as if it had called fork() itself.

Since the newly-created process is a child process, its fork() will return 0 thus it will fall into thte child branch. And the original process’s fork() will return the child process’s id so it will fall into the parent branch.

The output of p1 is not deterministic, as the child process’s printing statement can also come before the parent as well.

The wait() System Call

When we want a parent to wait for a child process to finish what it has been doing, we can use the wait() system call or its more complete sibling waitpid()

call the following program p2

int main(int argc, char *argv[])
{
	printf("hello world (pid:%d)\\n", (int) getpid());
	    int rc = fork();
	    if (rc < 0) {         // fork failed; exit
	        fprintf(stderr, "fork failed\\n");
	        exit(1);
	    } else if (rc == 0) { // child (new process)
	        printf("hello, I am child (pid:%d)\\n", (int) getpid());
	    } else {              // parent goes down this path (main)
					int wc = wait(NULL);
	        printf("hello, I am parent of %d (wc: %d)(pid:%d)\\n",
	                rc, wc, (int) getpid());
	}
	return 0;
}

the output will be