msdnguide's Avatar, Join Date: May 2011
Go4Expert Member
it is better to use vfork and then spawn. vfork does not creates a new process till the time we do spawn thereby saving system resources
gandhisagar's Avatar, Join Date: Apr 2011
Newbie Member
one simple improvement I would like to have in this nice article .

Code:
#include<stdio.h>
#include<unistd.h>

/* include types.h for  unix system dependent types */
#include <sys/types.h>

/* include it for string operations */
#include <string.h>

char buf[1024] ;

int main()
{
	pid_t pid;
	pid = fork();
	if(pid == -1)
	{
		sprintf(buf, "Error making Process!\n");
                write(1,buf,strlen(buf));
		return(-1);
	}
	if(!pid) 
	{
		sprintf(buf, "Hey this is parent , my pid is %d",getpid());
                write(1,buf,strlen(buf));
		sleep(1);
	}
	else
	{
		sprintf(buf, "Hey this is child , my pid is %d",getpid());
                write(1,buf,strlen(buf));
		sleep(1);
		return(0);
	}

    return 0 ;		
}

because printf() is "buffered," meaning printf() will group the output of a process together. While buffering the output for the parent process, the child may also use printf to print out some information, which will also be buffered. As a result, since the output will not be send to screen immediately, you may not get the right order of the expected result. Worse, the output from the two processes may be mixed in strange ways. To overcome this problem, you may consider to use the "unbuffered" write. .

Code:
#include <sys/types.h>
pid_t is defined in it .


Quote:
Jai Hind .
gandhisagar's Avatar, Join Date: Apr 2011
Newbie Member
Sir, vfork is generally used when you are expected to call "exec".
and fork has "Copy on write" mechanism now so fork even doesn't duplicate address space until needed.

Difference between the two is that, when vfork() is called, Parent leans it address space to Child and
parent process is suspended, This continues until the child process either exits, or calls exec(), at which point the parent process continues.

References :
Unix Internals ... uresh vahliya


"Jai Hind"
gandhisagar's Avatar, Join Date: Apr 2011
Newbie Member
Sir, vfork is generally used when you are expected to call "exec".
and fork has "Copy on write" mechanism now so fork even doesn't duplicate address space until needed.

Difference between the two is that, when vfork() is called, Parent leans it address space to Child and
parent process is suspended, This continues until the child process either exits, or calls exec(), at which point the parent process continues.

References :
Unix Internals ... uresh vahliya


"Jai Hindi"
jaan's Avatar, Join Date: Jun 2011
Newbie Member
very very Extremely useful post.....

Last edited by shabbir; 12Jun2011 at 08:43.. Reason: Confine links to signature