Fork rule #2 – the return

Let's take a look at the code we've used so far:

    if (fork() == -1)        FATAL("fork failed!\n");    printf("PID %d: Hello, fork.\n", getpid());    exit(EXIT_SUCCESS);

OK, we now understand from the first rule that the printf will be run twice and in parallel—once by the parent, and once by the child process.

But, think about it: is this really useful? Can a real-world application benefit from this? No. What we are really after, what would be useful, is a division of labor, that is to say, have the child perform some task or tasks, and the parent perform some other task(s), in parallel. That makes the fork attractive and useful.

For example, after the fork, have the child run the code of some function foo and the parent run ...

Get Hands-On System Programming with Linux now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.