相关疑难解决方法(0)

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

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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

Init
pre fork()Parrent PID:4788
pre fork()Child PID:0
Run Code Online (Sandbox Code Playgroud)

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

为什么printf("pre fork()");运行两次,init() …

c unix linux fork

5
推荐指数
1
解决办法
1460
查看次数

标签 统计

c ×1

fork ×1

linux ×1

unix ×1