Reputation: 477
in my assignment I am to input 'n' and create 'n' amount of child processes. From there the child processes execl into another program which has them sleep for a random number of seconds(between 0 and 9), then exits with the exit status of the random number. Once they exit, in the parent, I am to print the child's PID and the child's exit status. My issues are that I am unsure on how to get the PID or exit status without using IPC. Along with the "Child is dead..." out come out at the same time. This is what I've come up with now.
parent:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main()
{
char input[12];
int n, i, ch;
pid_t pid;
int status;
printf("Enter an integer: ");
fgets(input, 12, stdin);
if (input[10] == '\n' && input[11] == '\0') { while ( (ch = fgetc(stdin)) != EOF && ch != '\n'); }
rmnewline(input);
n = atoi(input);
for(i=0; i<=n-1; i++)
{
pid = fork();
if(pid == 0)
execl("/home/andrew/USP_ASG2/sleep", "sleep", NULL);
}
while(wait(NULL)>0)
{
if(WIFEXITED(status))
{
int exitstat = WEXITSTATUS(status);
printf("Child %d is dead with exit status %d\n", pid, exitstat);
}
}
}
child:
int main()
{
srand(time(NULL));
int r = rand() % 10;
printf("In child %d\n", getpid());
sleep(r);
exit(r);
}
current output: A couple things I noticed is the "Child is dead..." output all come back at the same time. When they surely be differnt.
xxxxxx@ubuntu:~/USP_ASG2$ ./q2
Enter an integer: 3
In child 15624
In child 15623
In child 15622
Child 15624 is dead with exit status 0
Child 15624 is dead with exit status 0
Child 15624 is dead with exit status 0
Upvotes: 0
Views: 6410
Reputation: 16540
suggest using waitpid() so you will know which child exited.
the fork()
function returns the pid of the child to the parent (read man page for fork()
)
To get/use exit status of child, wait()
or waitpid()
has a parameter that is a pointer to an int variable.
When the wait()
or waitpid()
returns to its' caller, the int variable will contain the exit status from the child.
Upvotes: 1