Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

c - Need to know how fork works?

I am trying the following C code:

int main()
{
    printf("text1
");
    fork();
    printf("text2
");
    return 0;
}

I was expecting to get the output where i get two "text1" and two "text2", like:

text1
text1
text2
text2

But, i am, instead, getting:

text1
text2
text2

only one "text1"??? Ok, if child process executes from the fork(), then why do i get two "text1" for following:

int main()  
{  
    printf("text1");  
    fork();  
    printf("text2
");  
    return 0;  
}  

the output now is:

text1text2  
text1text2 

If the child process starts after the fork, output should be:

text1  
text2  
text2  
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

fork() creates a new process by copying everything in the current process into the new process. That typically includes everything in memory and the current values of the CPU registers with some minor adjustments. So in effect, the new process gets a copy of the process's instruction pointer as well so it resumes at the same point where the original process would continue (the instruction following the fork()).


To address your update, printf() is buffered. Normally the buffer is flushed when it encounters a newline character at the end, ' '. However since you have omitted this, the contents of the buffer stays and is not flushed. In the end, both processes (the original and the child) will have the output buffer with "text1" in it. When it eventually gets flushed, you'll see this in both processes.

In practice, you should always flush files and all buffers (that includes stdout) before forking to ensure that this does not happen.

printf("text1");
fflush(stdout);
fork();

The output should look like this (in some order):

text1text2
text2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...