简体   繁体   English

unix fork()系统调用什么时候运行?

[英]Unix fork() system call what runs when?

void child(int pid){
    printf("Child PID:%d\n",pid);
    exit(0);    
}
void parent(int pid){
    printf("Parent PID:%d\n",pid);
    exit(0);
}

void init(){
    printf("Init\n");//runs before the fork
}


int main(){

    init();//only runs for parent i.e. runs once
    printf("pre fork()");// but this runs for both i.e. runs twice
    //why???

    int pid = fork();

    if(pid == 0){
        child(pid); //run child process
    }else{
        parent(pid);//run parent process
    }
    return 0;
}

output: 输出:

Init
pre fork()Parrent PID:4788
pre fork()Child PID:0

I have a process in a Unix OS (Ubuntu in my case). 我在Unix操作系统中有一个进程(在我的例子中是Ubuntu)。 I can't for the life of me understand how this works. 我不能为我的生活理解这是如何运作的。 I know the fork() function splits my programs in two processes but from where? 我知道fork()函数在两个进程中分割我的程序但是从哪里来? Does it create a new process and run the whole main function again, and if so why did the init() only run once and the printf() twice? 它是否创建了一个新进程并再次运行整个main函数,如果是这样,为什么init()只运行一次而printf()两次?

Why does the printf("pre fork()"); 为什么是printf("pre fork()"); run twice and the init() function only once? 运行两次, init()函数只运行一次?

There's only one process until the fork. 在fork之前只有一个进程。 That is, that path is executed only once. 也就是说,该路径只执行一次。 After the fork there are 2 processes so the code following that system call is executed by both processes. fork之后有2个进程,因此系统调用之后的代码由两个进程执行。 What you ignore is that both terminate and both will call exit . 你忽略的是两个都终止,两者都会调用exit

In your code you're not flushing stdio . 在您的代码中,您不会刷新stdio So both processes do that (exit flushes stdio buffers) - that's why you're seeing that output. 所以这两个进程都这样做(退出刷新stdio缓冲区) - 这就是你看到输出的原因。

Try this: 试试这个:

printf("pre fork()\n");
                  ^^ should flush stdout

Or maybe 或者可能

printf("pre fork()\n");
fflush(stdout);

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

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