关于 linux 中的 fork 系统调用
Regarding fork system call 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;
}
这是我的输出:
我的 CS 教授的笔记如下:
After a new child process is created, both processes will execute the
next instruction following the fork()
system call. Please note that
Unix will make an exact copy of the parent's address space and give it
to the child. Therefore, the parent and child processes have separate
address spaces.
因此,我非常困惑,为什么它不仅会再次输出当前目录,还会再次输出"hello"?我认为它会这样做的唯一可能原因是说 "copies the address space" 只是 re-运行 fork 之前的所有命令的行,但这没有任何意义。
当您使用 printf
时,输出会被缓冲。因此,在 printf
.
之后立即执行 fflush
或 \n
添加 fflush
或 \n
虽然会强制刷新缓冲区并输出到屏幕。这发生在分叉之前,因此只打印一次。
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.
好的,我正在 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;
}
这是我的输出:
我的 CS 教授的笔记如下:
After a new child process is created, both processes will execute the next instruction following the
fork()
system call. Please note that Unix will make an exact copy of the parent's address space and give it to the child. Therefore, the parent and child processes have separate address spaces.
因此,我非常困惑,为什么它不仅会再次输出当前目录,还会再次输出"hello"?我认为它会这样做的唯一可能原因是说 "copies the address space" 只是 re-运行 fork 之前的所有命令的行,但这没有任何意义。
当您使用 printf
时,输出会被缓冲。因此,在 printf
.
fflush
或 \n
添加 fflush
或 \n
虽然会强制刷新缓冲区并输出到屏幕。这发生在分叉之前,因此只打印一次。
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.