简体   繁体   English

关于linux中的fork系统调用

[英]Regarding fork system call in linux

Okay I am working with the following C/C++ code in linux: 好的,我正在使用linux中的以下C / C ++代码:

int main() {
    printf("hello");
    Pid = fork();
    if (pid > 0)
            printf("I’m the parent!");
    else
            printf("I’m the child");
    return 0;
}

Here is my output: 这是我的输出: 程序输出截图

My notes from my CS prof say the following: 我的CS教授的笔记说如下:

After a new child process is created, both processes will execute the next instruction following the fork() system call. 创建新的子进程后,两个进程将执行fork()系统调用之后的下一条指令。 Please note that Unix will make an exact copy of the parent's address space and give it to the child. 请注意,Unix将精确复制父级的地址空间并将其提供给孩子。 Therefore, the parent and child processes have separate address spaces. 因此,父进程和子进程具有单独的地址空间。

For this reason, I am extremely confused as to why it would not only output the current directory again but also the "hello" again? 出于这个原因,我非常困惑为什么它不仅会再次输出当前目录而且还会再次输出“你好”? the only possible reason I could think that it would do this is the line that says it "copies the address space" is simply re-running all the commands before the fork but that doesn't make any sense. 我认为它会做到这一点的唯一可能原因是它说“复制地址空间”只是在fork之前重新运行所有命令,但这没有任何意义。

When you use printf , the output is buffered. 使用printf ,输出将被缓冲。 So, do a fflush or \\n right after printf . 所以,在printf之后做一个fflush\\n

Adding the fflush or \\n though forces the buffer to be flushed and outputted to the screen. 添加fflush\\n虽然强制刷新缓冲区并输出到屏幕。 This happens before the fork and hence is only printed once. 这发生在前叉之前,因此只打印一次。

C99 7.19.2p2 C99 7.19.2p2

Whether the last line requires a terminating new-line character is implementation-defined. 最后一行是否需要终止换行符是实现定义的。

It doesn't define what happens if a terminating new-line character isn't provided. 它没有定义如果没有提供终止换行字符会发生什么。 Since the standard doesn't define the behavior, the behavior is undefined. 由于标准未定义行为,因此行为未定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM