I have a problem to make a program that is going to create n processes.
The first process, which is initial program, creates the second process, which in turn creates the third process, and so on until the nth process is created.
my code so far looks like this and when i run it some child processes create more then one child process (every process should create only one child!)
any suggestions how to fix this?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream.h>
static int n;
void makeprocess();
int main (int argc, char *argv[])
{
if (argc != 2) {
printf ("Usage: %s <#processes>\n", argv[0]);
exit (1);
}
n = atoi (argv[1]);
if (n > 10 && n < 1) // create up to 10 new processes
{
printf ("Wrong number of processes (> 10)\n");
exit (1);
}
if (fork() == -1) { // create 1st process
perror ("fork");
exit (1);
}
n--;
printf("n:%d process ID:%d parent ID:%d\n",
n, getpid(), getppid());
makeprocess();
return 0;
}
void makeprocess()
{
n--;
cout <<"n "<<n<<endl;
if (fork() == -1) {
perror ("fork");
exit (1);
}
printf("n:%d process ID:%d parent ID:%d\n",
n, getpid(), getppid());
if (n > 0) {
makeprocess();
}
}