I'm writing a program where I have to give in the command line an integer that define the number of consecutive children. For exemple, if the number is 3, the first child will create a second child that will create a third child.
I have no idea how to do it on C# since the number of consecutive children is a number passed by the user ( the value on argv[1] when the prog is called. ex.: ./program 3 )
Also how to handle the wait of the respective father.
There is a difference between C and C++. C++ is (almost) a superset of C. And C# is something entirely different.
And your question:
1 2
int num; //Your number of children
while(fork() == 0 && --num >= 0) ;
EDIT: Note that there is no error checking, so if you create less children then no one will know. Also, you'll probably want to save the PID of the children.
'--' is predecrement. It subtracts one from num before comparing it to 0 (If you didn't know this I'm not sure why you're working with fork.)
Num is declared before the while loop.
You can put it all in the while statement:
1 2 3
int num; //Your number of processes
PID child; //This process's child's PID
while((PID = fork()) == 0 && --num > 0);
fork() creates a perfect copy of the current process, with the only difference being the return value. 0 for children, and the PID of the child for parents.
Synching your processes will be a lot harder. You'll need to use something like shared memory ( http://www.cs.cf.ac.uk/Dave/C/node27.html ), or sockets to have the processes communicate.