Child creates another child that creates another child... and so on[How to?]

Hi guys,

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.

could someone give me a hand ?

[]'s
What do you mean by children?

Also, is this actually a C++ question? This is a C++ forum.
Yep, C or C++, I think there's no difference.

By child I mean when you create a process through the command "fork()".

Am I in the wrong forum ?
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.
Last edited on
BlackSheep, thank you man. I'm working with C ( not c#, sorry about that ).

But since I'm still a noob in C, could you explain me that while ?

While fork()==0 and --num >=0 ?

what is the --num ? I tought the --variable was only to decrease a variable, not to use in a declaration like that...

and I did't understand the while fork()==0 statement...

Inside that while I should put something like

1
2
pid[num]=fork();
--num 


???
and what about the wait() ??
'--' 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.
Last edited on
Topic archived. No new replies allowed.