A revelation of a small program about FORK

xiaoxiao2021-03-06  17

A few days ago, some people in the forum have asked such a question:

#include #include

int

main

() {

for

(

INT i

=

0

I

<

3

I

) {

Int PID

= Fork

();

IF

(PID)

==

0

) {

PRINTF

(

"Child / N"

}

Else

{

PRINTF

(

"Father / N"

}}

Return

0

}

What is the output result?

At first glance, I think of the result is that the result is

3 pairs of Child

-father, just order uncertain, and according to the statement of advanced programming in UNIX, the contents of the two outputs may also occur in the case where the contents may also occur.

However, in UNIX test, it was found that the output was actually

7 pairs of Child

-father. Why is this so? I have finally understood this simple problem. In fact, this problem is writing

/ Understand that compilation seems to be clear, the problem is here

FOR cycle.

1.i

=

0, the parent process enters

For cycle, at this time due to the role of the Fork, two processes of the father and son

(Recorded as F0, respectively

/ S0

), Output father and child, then, the two perform subsequent code, what is the following code?

?

Return

0

Of course, because

The existence of the for loop, the subsequent code is the add instruction and a JUMP instruction, so the parent-child process will enter i

=

1 situation;

2.i

=

At 1, the parent process continued to divide the father and son.

(Remember to f1, respectively

/ S1

And i

=

0 When the child process, it will also be divided into two processes.

(Remember to fs01, respectively

/ Ss01

), Then all these processes enter I

=

2;

3.

.... The process is similar to the above, no need to say more, I believe that everything is already clear, according to the above mark method, i

=

2 will generate F2

/ S2

FS12

/ Ss12

FFS012

/ Sfs012

, FSS012

/ Sss012

.

Therefore, the final result is output

7 pairs of Child

/ Father. Its corresponding mathematical formula is:

1

2

4

...

2

^ (n

-

1

) =

2

^ n

-

1

But then say it back, this is

The practice of using FORK is not worth recommending. The research research is still, the actual application will probably lead to a lot of trouble, you need to be cautious.

转载请注明原文地址:https://www.9cbs.com/read-41723.html

New Post(0)