forking n number of processes in a loop and not 2^n

Hi,

Am working on linux. while forking in a loop how to avoid the child process from forking..for example

int n = 5;
pid_t pid;
pid_t ch_pid[5];

/exactly wanted to create n processes and not 2^n processes/

for(i = 0; i < n;i++)
{
if(pid = fork())
{
/* parent process */
ch_pid[n] = pid;
waitpid(pid);
}
else if(pid == 0)
{
/child process/
spawn_process(ch_pid[n], n);
/In spawn_process() i will call exec()/
}
else
{
/Handle error/
}
}

  1. Once the child process calls exec(), do I need to do something to restrict the child process from forking?

  2. What will be the stack size allocated for the child processes?

Thanks,
Anand

Hi,

Am working on linux. while forking in a loop how to avoid the child process from forking..for example

int n = 5;
pid_t pid;
pid_t ch_pid[5];

/exactly wanted to create n processes and not 2^n processes/

for(i = 0; i < n;i++)
{
if(pid = fork())
{
/* parent process */
ch_pid[n] = pid;
waitpid(pid);
}
else if(pid == 0)
{
/child process/
spawn_process(ch_pid[n], n);
/In spawn_process() i will call exec()/
}
else
{
/Handle error/
}
}

  1. Once the child process calls exec(), do I need to do something to restrict the child process from forking?

  2. What will be the stack size allocated for the child processes?

Thanks,
Anand

This is how to control the number of children. I'll let you work out calling execl()

#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

int foo(const char *whoami)
{
	printf("I am a %s.  My pid is:%d  my ppid is %d\n",
			whoami, getpid(), getppid() );
	return 1;
}

int main(int argc, char **argv)
{
	int n=atoi(argv[1]);
	int i=0;
	int status=0;

	if (n==0) n=2;
	printf("Creating %d children\n", n);
	foo("parent");
	for(i=0;i<n;i++)
	{
		pid_t pid=fork();
		if (pid==0) /* only execute this if child */
		{
			foo("child");
			exit(0);
		}
		wait(&status);  /* only the parent waits */
	}
	return 0;
}

to prevent the child from spawning another child, kill that child before it loops!
in other words,don't ever let it loop the for( ; ; ), or add if (pid !=0 ) before the fork () call

Hi guys ,

thnk u for ur help
i don't want to kill the child processess
"if (pid !=0 )" helped me a lot..
thnk u once again..