要知道叉是如何工作的? [英] Need to know how fork works?

查看:85
本文介绍了要知道叉是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想下面的C code:

  INT的main()
{
    的printf(文本1 \\ n);
    叉子();
    的printf(文本2 \\ n);
    返回0;
}

我期待得到输出在那里我得到两个text1中的两个文本2,如:

 文本1
文本1
文本2
文本2

不过,我是,相反,越来越:

 文本1
文本2
文本2

只有一个text1中?
好吧,如果子进程从叉(执行),那么为什么我得到两个text1中的以下内容:

  INT的main()
{
    的printf(text1中);
    叉子();
    的printf(文本2 \\ n);
    返回0;
}

输出的是现在:

  text1text2
text1text2

如果子进程后叉开始,输出应该是:

 文本1
文本2
文本2


解决方案

叉()创建通过复制当前进程一切都变成新的进程的新进程。通常包括在存储器一切并用一些小的调整CPU寄存器的当前值。因此,实际上,新进程得到该进程的指令指针的一个拷贝,以及因此恢复在同一点其中原始进程将继续(继叉()中的指令)。


要解决您的更新,的printf()缓冲。通常情况下,则将刷新缓冲区,当它到了最后,的'\\ n'遇到一个换行符。不过既然你已经忽略这一点,缓冲区的内容保持,不刷新。最终,这两个过程(原件和孩子)将在其text1中的输出缓冲区。当它最终被刷新,你会看到这两个进程。

在实践中,你应该始终刷新文件和所有缓冲区(包括标准输出)分叉,以确保不会发生这种情况了。

 的printf(text1中);
fflush(标准输出);
叉子();

输出应该是这样的(在某些顺序):


text1text2
文本2

I am trying the following C code:

int main()
{
    printf("text1\n");
    fork();
    printf("text2\n");
    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\n");  
    return 0;  
}  

the output now is:

text1text2  
text1text2 

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

text1  
text2  
text2  

解决方案

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, '\n'. 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

这篇关于要知道叉是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆