C – fork a child process using vfork()

Creates a child process using vfork(). The child increments a global variable (glob) and a local one (var) and returns the corresponding process id of the respective process. With vfork() the child uses the same environment as the parent, so if the child changes these values, the parent uses the changed ones too.

/* creates a child process using vfork().
 * the child increments a global variable (glob)
 * and a local one (var) and returns
 * the corresponding process id of the 
 * respective process .
 * with vfork() the child uses the same
 * environment as the parent, so if
 * the child changes these values, the 
 * parent uses the changed ones too.*/
#include <sys/types.h> 
#include <stdlib.h>
#include <unistd.h>

int glob=66;
char buf[]="string to be 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 to stdout failed\n");
	    exit(1);
	    /* normal exit */
	}
    printf("i'm gonna give birth to a child now\n");
    if ((pid=vfork())<0)
	/* vfork - create a child process and block the parent */
    	{
	    printf("damn. child died at birth.\n");
	    exit(2);
	}
    else
	if (pid==0)
	/* vfork() 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++;
	    }
    printf("My pid is %d, glob=%d, var=%d\n", getpid(), glob, var);
    exit(0);
}