I'm trying to write a program where, based on a user input value 'n', I'm going to fork that many processes to run simultaneously. In addition, each child is trying to exec to another file that I've created, that will generate a x sleep time, and a x exit value. Ultimately, when a child dies, the parent needs to print the pid and exit_status. The important part is making sure that children death is x, and not concurrent. So far, there's two things I can't figure out.
- Getting my execl to run my sleep.c file (as provided below).
- Getting the children to fork and die randomly, not in an orderly fashion, and as a result printing who died, with their generated random exit status.
I have two files, Sleep.c and Ranchild.c.
SLEEP.C
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
/* Generated random sleep time, and return random exit value */
int main()
{
/* Calculate A Random Time To Sleep 1 - 10 Seconds*/
srand(time(NULL));
int r = (rand() % 10) + 1;
printf("Sleep Time: %d\n", r);
sleep(r);
/* Calculate A Random Exit Value */
int r2 = (rand() % 30) + 1;
exit(r2);
}
RANCHILD.C
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
int main()
{
/* Get User Input */
int i, n;
printf("Please Enter An Integer!\n");
/* Test User Input */
if(!scanf("%d", &n)) {
printf("Invalid Input!\n");
return -1;
}
/* Initialize Needed Variables */
pid_t pid[n];
int status, exit_status;
for(i = 0; i < n; i++) {
if((pid[i] = fork()) < 0) {
perror("Fork Failed!");
return -2;
}
if(pid[i] == 0) {
execl("sleep", "sleep", (char *)0);
} else {
/* Print Child Results */
if (waitpid(-1, &status, WNOHANG) == 0) {
if(WIFEXITED(status)) {
exit_status = WEXITSTATUS(status);
printf("Exit Status From %d was %d!\n", pid[i], exit_status);
}
}
}
}
exit(0);
}
It never manages to exec to the Sleep file, and a sample of the result is this:
3
Exit Status From 27369 was 0!
Exit Status From 27370 was 0!
Exit Status From 27371 was 0!
Sleep Time: 4
Sleep Time: 4
Sleep Time: 4
Your help is greatly appreciated!!
statusuntil you callwait. I don't see a call towait. - William Pursellwaitand thus create one child at a time in your loop. - Ducksleep.ccode, since the child processes are all likely to be started at the same time (same second), usingtime()to seedsrand()is unlikely to work well. Usegetpid()too; that is guaranteed to be unique. You might also play with the sub-second part of the result of one of the sub-second timing functions (clock_gettime()orgettimeofday(), for example). But on a multi-CPU chip, the PID is still unique and the time is not necessarily unique. You have the same problem with the exit statuses, of course; all the children are likely to exit with the same status. - Jonathan Lefflerwaitpid()call rather than just anif. And the whole waiting business should be done after you've created all the children, not as you create each one. - Jonathan Leffler