程序中fork()的定义

kau*_*nav 0 unix operating-system system-calls

我研究过fork()调用创建一个新程序,从程序中调用它.

但是在以下两个非常相似的程序中,它表现出不同的行为.为什么是这样?

计划1:

#include <stdio.h>
#include <unistd.h>

int main(int argc, char* argv[])
{
    printf("Start %d ", getpid()) ; 
    pid_t pid = fork() ;
    if (pid > 0)
        printf("Parent %d ", getpid()) ; 
    if (pid == 0)
        printf("Child %d ", getpid()) ;
    return 0 ; 
}
Run Code Online (Sandbox Code Playgroud)

输出为:

Start 1104 Parent 1104 Start 1104 Child 1105
Run Code Online (Sandbox Code Playgroud)

计划2:

#include <stdio.h>
#include <unistd.h>

int main(int argc, char* argv[])
{
    printf("Start %d \n", getpid()) ; 
    pid_t pid = fork() ;
    if (pid > 0)
        printf("Parent %d \n", getpid()) ; 
    if (pid == 0)
        printf("Child %d \n", getpid()) ;
    return 0 ; 
}
Run Code Online (Sandbox Code Playgroud)

输出为:

Start 1126 
Child 1127 
Parent 1126 
Run Code Online (Sandbox Code Playgroud)

只需包含"\n"即可更改输出.是什么导致这个?

Dav*_*rtz 5

如果您要在父级和子级中使用流,则需要先将其刷新fork.否则,缓冲区中剩余的内容将被刷新两次,一次由父级刷新,一次由子级刷新.

此外,您不应该从main父母和孩子都返回.如果这样做,任何atexit处理程序将运行两次.这导致了过去的安全隐患.父母或孩子应该调用_exit或成功调用其中一个exec函数.