加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

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

发布时间:2020-12-13 19:28:05 所属栏目:Linux 来源:网络整理
导读:void child(int pid){ printf("Child PID:%dn",pid); exit(0); }void parent(int pid){ printf("Parent PID:%dn",pid); exit(0);}void init(){ printf("Initn");//runs before the fork}int main(){ init();//only runs for parent i.e. runs once printf

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

void init(){
    printf("Initn");//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;
}

输出:

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

我在Unix操作系统中有一个进程(在我的例子中是Ubuntu).我不能为我的生活理解这是如何运作的.我知道fork()函数在两个进程中分割我的程序但是从哪里来?它是否创建了一个新进程并再次运行整个main函数,如果是这样,为什么init()只运行一次而printf()运行两次?

为什么是printf(“pre fork()”);运行两次,init()函数只运行一次?

最佳答案
在fork之前只有一个进程.也就是说,该路径只执行一次. fork之后有2个进程,因此系统调用之后的代码由两个进程执行.你忽略的是两个都终止,两者都会调用exit.

在您的代码中,您不会刷新stdio.所以这两个进程都这样做(退出刷新stdio缓冲区) – 这就是你看到输出的原因.

试试这个:

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

或者可能

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读