C – forking a child process using fork()

Creates a child process using fork(). The child increments a global variable (glob) and a local one (var) and returns the corresponding process id of each process. With fork() the child DOES NOT USE the same variables as the parent, so if the child changes these values, the parent still keeps his.

/* creates a child process using fork(). the child increments a global variable (glob)
 * and a local one (var) and returns the corresponding process id of each process.
 * with fork() the child DOES NOT USE the same variables as the parent, so if
 * the child changes these values, the parent still keeps his. */
#include <sys/types.h> 
#include <stdlib.h>
#include <unistd.h>

int glob=66;
char buf[]="string outputed to stdout\n";

int main(void)
{
    int var=88;
    pid_t pid;
/* The `pid_t' data type is a signed integer type which is capable of
 * representing a process ID.  In the GNU library, this is an `int'.
 */
    if (write(STDOUT_FILENO, buf, sizeof(buf)-1)!=sizeof(buf)-1)
/* ssize_t write(int fd, const void *buf, size_t count);
 * writes up to count bytes to the file referenced by the file descriptor fd from the buffer starting at
 * buf
 * On  success, the number of bytes written are returned
 */
    /* if it didn't wrote the whole string to stdout */
    	{
	    printf("write error\n");
	    exit(1);
	    /* normal exit */
	}
    printf("i'm gonna give birth to a child now\n");
    if ((pid=fork())<0)
	/* fork - create a child process. Does NOT block the parent. 
	 * the parent continues execution immediatly after the child
	 * process was created (man fork) */
    	{
	    printf("damn. child died at birth.\n");
	    exit(2);
	}
    else
	if (pid==0)
	/* fork() returns pid=0 to the child process and the pid of the child
	 * to the parrent. so, if pid=0, we are in the child process */
	    {
		printf("Lookie here, i am a kid and my pid is %d. My parent is %d.\n", getpid(),getppid());
		/* getpid  returns the process ID of the current process.
		 * getppid returns the process ID of the parent of the current process. */
		glob++;
		var++;
	    }
/*    wait(); */
/* wait() makes the parent stop the execution until the child has died one way or another
 * can be used to show that with fork() they don't share the same environment */
    printf("My pid is %d, glob=%d, var=%d\n", getpid(), glob, var);
    exit(0);
}