You guys are making this much harder than it needs to be. Let's start by forking
one process and storing its pid:
Code:
#include <stdio.h>
#include <unistd.h>
void main()
{
int pid, parentpid, childpid;
parentpid=getpid();
printf("I am the parent process and my pid is %d\n", getpid());
if (pid=fork()) {
childpid=pid;
} else {
printf("I am a child process and my pid is %d\n", getpid());
exit(0);
}
printf("I am still the parent process and my pid is %d\n", getpid());
exit(0);
}
Here the child process just displays its pid then exits. You will probably want to do more with your child processes, but after your children take care of business they must exit so they participate in any further forking. Also in my example the parent process exits fairly quickly. This means that init will inherit the child process and will reap it when it dies. If I wanted to keep the parent around, I would need to insure that it issues wait() calls for each child who dies. If I didn't do this, the children would become zombies. I usually just let the parent die.
Once we have some code that does what we want, if we want to do it n times, we use a
loop:
Code:
#include <stdio.h>
#include <unistd.h>
void main()
{
int n, pid, parentpid, childpids[10];
parentpid=getpid();
printf("I am the parent process and my pid is %d\n", getpid());
for(n=0; n<5; n++) {
if (pid=fork()) {
childpids[n]=pid;
} else {
printf("I am a child process and my pid is %d\n",
getpid());
exit(0);
}
}
printf("I am still the parent process and my pid is %d\n", getpid());
exit(0);
}
As requested by the OP, the children's pids are recorded in an array. But I still just let the parent die.