Interesting Process Creation function fork ()

Source: Internet
Author: User

When I encountered such a problem when I was doing a pen test for a company, the description is as follows:

How many "-" characters will be output in the following code?

#include<stdio.h>#include<sys/types.h>#include<unistd.h>int main(){int i;for(i=0;i<2;i++){fork();printf("-\n");}return 0;}

Here, we only provide an introduction. Next we will introduce fork () and solve this problem.


Fork () function

# Include <unistd. h>/* return value: 0 is returned for the child process, and the ID of the child process is returned for the parent process. If an error occurs,-1 */pid_t fork (void) is returned );
A new process created by fork is called a child process ). The fork function is called once, but returns two. The Return Value of the child process is 0, while that of the parent process is the ID of the new process. The reason for returning the child process ID to the parent process is:Because a process can have multiple sub-processes, and no function allows a process to obtain the ID of all its sub-processes. Fork causes the sub-process to get the return value 0:A process has only one parent process, so the child process can always call getpid to obtain the ID of the parent process.

There are already too many processes in the system, or the total number of processes with the actual user ID exceeds the system limit.

Fork has the following usage:

(1)A parent process needs to copy itself so that the parent and child processes can execute different code segments at the same time.This is common in network service processes-the parent process waits for client service requests. When such a request arrives, the parent process calls fork to process the request. The parent process continues to wait for the next service request to arrive.

(2)A process needs to execute a different program.This is a common case for shell. The child process immediately calls exec after returning from fork.

In short, multithreading is implemented. Multi-threaded implementation in C language requires self-control. This is more complicated than Java.


Note:Fork does create a child process and completely copies the parent process,The sub-process starts to execute the command after fork.. The reason is also logical. If the sub-process also executes all the commands from the beginning to the end of the main, it will certainly create a sub-process when it executes the fork command, and the sub-process will be endless, in this case, this small program can create countless processes to paralyze your computer, so the fork author will certainly not do this.

Here, we will take the most classic fork code example:

# Include <stdio. h> # include <sys/types. h> # include <unistd. h> int main () {pid_t pid = fork (); // The program starts to split from here, and the parent and child processes run once from this sentence if (pid> 0) {sleep (2); printf ("this is parent process: process ID is % d \ n", getpid ();} else if (pid = 0) {printf ("this is child process: process ID is % d \ n", getpid ();} else {printf ("error! \ N ") ;}return 0 ;}

Result:



Now back to the program at the beginning, how many "-" are output "-"? The original code will be parsed cyclically into the following format:

int main(){fork();printf("-\n");fork();        printf("-\n");return 0;}

Analysis:First, parent process a executes the first fork () function, and then generates a sub-process B. At this time, both A and B are concurrently executed, both of which execute printf ("-"); output two "-" first, and then process a and process B both execute the fork () function. Therefore, a creates sub-process C and B creates sub-process D, now there are a total of four processes, ABCD, and then execute the following printf ("-");, Print four times, output four "-", a total of six "-".

For example:


As you can see, printf ("-") is executed six times in total ("-").


Okay. Let's take a look at this interesting question:

#include<stdio.h>int main(){  fork();  fork()&&fork()||fork();  fork();}
How many processes are there?

Analysis: There are three main points to solve this problem: 1. the sub-process starts to execute the command after fork; 2. the fork Parent and Child processes return different values. 3 for "A & B", if A is 0, B is not executed.

It is too complicated to describe in a language. The last one is intended for readers to understand:



The total number of processes at the end is determined by the number of sub-nodes. Obviously, there are 20 in total. The key point is that on the third layer of the tree, C and D are sub-processes, and the values returned by both are 0. Therefore, the expressions after "&" will not be executed, then execute the last fork () function. However, if the returned values of the parent processes A and B are greater than 0, the following "fork () | fork ()" will be executed ()". The analysis is over. If you have any questions, leave a message.


References:

UNIX advanced environment programming


Reprinted please indicate the source: http://blog.csdn.net/lavorange/article/details/38961247


Interesting Process Creation function fork ()

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.