Fork function __ Function

Source: Internet
Author: User

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
* *

  


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.