System Calls fundamentals and what will be out put on this program [closed]
I want to know the output from this program it about system call. I try to understand but it's hard.
int main (void) {
pid_t pid;
pid = fork();
if (pid > 0) {
int i;
for (i = 0; i < 5; i++) {
printf(" I AM VU : %d\n", i);
sleep(1);
}
exit(0);
}
else if (pid == 0) {
int j;
for (j = 0; j < 5; j++) {
printf(" I have no child: %d\n", j);
sleep(1);
}
exit(0);
} else {
fprintf(stderr, "can't fork, error %d\n", errno);
exit (EXIT_FAILURE);
}
}
After you get this code to compile and run, the parent will output something like:
I AM VU : 0
I AM VU : 1
I AM VU : 2
I AM VU : 3
I AM VU : 4
The single child will output something like:
I have no child: 0
I have no child: 1
I have no child: 2
I have no child: 3
I have no child: 4
The five lines from the child will almost certainly be mixed up with the parent's output lines, so you'll see something like this on the screen:
I AM VU : 0
I have no child: 0
I AM VU : 1
I have no child: 1
I have no child: 2
I have no child: 3
I AM VU : 2
I have no child: 4
I AM VU : 3
I AM VU : 4
If the fork() fails, the program will output something like:
can't fork xx
where xx is errno.
NOTE I don't think of fork( )
as a system call but as a call to a library function. Small difference in practice and effect, but still.
'man fork' will answer questions on what fork returns.
Compile the code and use 'strace -f a.out' to follow what it's doing.
I'm not sure what that program is looping and sleeping for. My guess is it's just to demonstrate that the order of the output from the two processes can't be predicted.
精彩评论