We need to explain what this C-code does but i dont really get the hang of it.
Especially at that for loop where it breaks. anybody cares to explain? it would be of great help?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main (int argc, char *argv[]) {
pid_t childpid = 0;
int i, n;
if (argc != 2){ /* check for valid number of command-line arguments */
fprintf(stderr, "Usage: %s processes\n", argv[0]);
return 1;
}
n = atoi(argv[1]);
for (i = 1; i < n; i++)
if (childpid = fork())
break;
fprintf(stderr, "i:%d process ID:%ld parent ID:%ld child ID:%ld\n",
i, (long)getpid(), (long)getppid(), (long)childpid);
return 0;
}
Update:EDIT
sorry for the above edit^ it was an error
Copyright © 2024 QUIZLS.COM - All rights reserved.
Answers & Comments
Verified answer
To follow this you need to understand how fork() returns. If the fork() function is successful then it returns twice. Once in the child process with return value ’0′ and then it returns in the parent process with child’s PID as return value. This behavior is because of the fact that once the fork is called, child process is created and since the child process shares the text segment with parent process and continues execution from the next statement in the same text segment.
To understand this next part, you need to know how C works with True/False. Basically 0 is False and non-Zero is True:
So the 0 return in the Child would cause the loop to continue because the if() resolves to False and Break is not called--now the Child will be the parent in the next call and it will stop
The child ID returned in the parent process makes the if() TRUE and calls break; and then falls out of the loop and prints the information to standard error
In a nut shell the parent stops, and the child continues for one loop iteration, but stops the next time as the parent.
Regarding your question about the fork and the child continuing. The following statement is an assignment, not an equality check which would require ==
if (childpid = fork())
break;
So (childpid = fork()) equates to 0 or FALSE and the logic becomes
if (FALSE)
break;
Hope that helps.
You run the programme with a number, n, on the command line.
The for-loop runs n times.
For each one of them, the programme calls the "fork" function which creates another process as a 'clone' of itself. This is a "child" process.
Inside the child, the code breaks out of the loop, so that the spawned child does not start spawning its OWN children.
Meanwhile the original parent process prints a report about each child it created.