Using the fork system call

The signature of the fork is simplicity itself:

pid_t fork(void);

This looks trivial, but you know the saying the devil lies in the details! Indeed, we shall bring out several subtle, and not-so-subtle, pointers regarding the correct usage of this system call.

To begin to understand how fork works, lets write a simple C program (ch10/fork1.c):

int main(int argc, char **argv){    fork();    printf("Hello, fork.\n");    exit (EXIT_SUCCESS);}

Build and run it:

$ make fork1gcc -Wall -c ../../common.c -o common.ogcc -Wall   -c -o fork1.o fork1.cgcc -Wall -o fork1 fork1.c common.o$ ./fork1 Hello, fork.Hello, fork.$ 

The fork will, on success, have created a new child process.

A key programming rule: never assume an API succeeds, ...

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.