you probably want to wait for the child to exit
Code:
#include <unistd.h> /* Symbolic Constants */
#include <sys/types.h> /* Primitive System Data Types */
#include <errno.h> /* Errors */
#include <stdio.h> /* Input/Output */
#include <sys/wait.h> /* Wait for Process Termination */
#include <stdlib.h> /* General Utilities */
#include <time.h>
static void Usage(const char* prog)
{
printf("Not enough arguments\n");
printf("Usage:\n");
printf("%s <Number>\n", prog);
printf("\t where <Number> is number of child processes to start\n");
return;
}
int main(int argc, char* argv[])
{
pid_t childpid; /* variable to store the child's pid */
int retval; /* child process: return code */
int status; /* parent process: child's exit status */
int count;
int childs;
srand(time(NULL));
if(argc < 2)
{
Usage(argv[0]);
exit(0);
}
childs = (int)strtol(argv[1],NULL,10);
for(count=0; count < childs;count++)
{
/* now create new process */
childpid = fork();
if (childpid >= 0) /* fork succeeded */
{
if (childpid == 0) /* fork() returns 0 to the child process */
{
printf("CHILD: I am the child process!\n");
printf("CHILD: Here's my PID: %d\n", getpid());
printf("CHILD: My parent's PID is: %d\n", getppid());
printf("CHILD: The value of my copy of childpid is: %d\n", childpid);
printf("CHILD: Sleeping for 1 second...\n");
sleep(1); /* sleep for 1 second */
retval = getpid()%255;
printf("CHILD: Goodbye! retval=%d\n",retval);
exit(retval); /* child exits with random return code */
}
else /* fork() returns new pid to the parent process */
{
if(count == 0)
{
printf("PARENT: I am the parent process!\n");
printf("PARENT: Here's my PID: %d\n", getpid());
}
printf("PARENT: The value of my copy of childpid is %d\n", childpid);
}
}
else /* fork returns -1 on failure */
{
perror("fork"); /* display error message */
exit(0);
}
}
for(count=0; count < childs;count++)
{
printf("PARENT: I will now wait for my child %d to exit.\n",count);
wait(&status); /* wait for child to exit, and store its status */
printf("PARENT: Child's exit code is: %d\n", WEXITSTATUS(status));
}
printf("PARENT: Goodbye!\n");
exit(0); /* parent exits */
}