The fork () system call is a system call under Unix that creates a subprocess on its own process, one call, two returns, or a subprocess if the return is 0, or a parent process (the return value is the PID of a subprocess) if the return value is >0.
Another important thing is that at the Call of Fork (), the entire parent process space is copied to the child process in its original mode, including instructions, variable values, program call stacks, environment variables, buffers, and so on.
how many '-' does the run in Linux program output?
int main (void) {
int i;
for (i = 0; i < 2; i++) {
fork ();
printf ("-");
}
return 0;
}
A: If you are familiar with the mechanism of fork (), this problem is not difficult, the output should be 6 "-", but in fact, the program will be very tricky output 8 "-".
printf ("-"); put "-" into the cache, and there is no real output, in the fork, the cache is copied to the child process space, so, there are two more, it becomes 8, instead of 6.
So let's change the above procedure to the following:
int main (void) {
int i;
For (i=0 i<2; i++) {
fork ();
Note: The following printf has "n"
printf ("ppid=%d, pid=%d, i=%d n", Getppid (), Getpid (), i);
Sleep (10); Let the process stay for 10 seconds so we can view the process tree return
0 with Pstree
.
/* So, the above program will output the following results
ppid=8858, pid=8518, i=0
ppid=8858, pid=8518, I=1 ppid=8518
, pid=8519, i=0
ppid=8518, pid=8519, I=1
ppid=8518, pid=8520, I=1 ppid=8519
, pid=8521, i=1
* *