简体   繁体   English

在fork()进程中没有针对父进程的操作时会发生什么?

[英]What happens when there are no actions for parent process during fork() processes?

I have the following example code: 我有以下示例代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>

int main (){
    printf("hello world (pid:%d)\n", (int)getpid());
    int rc = fork();

    if(rc < 0){ //fork failed; exit
        fprintf(stderr, "fork failed\n");
        exit(1);

    } else if (rc == 0) { //child new process
        printf("hello, i am child (pid:%d)\n", (int)getpid());
        char *myargs[3];
        myargs[0] = strdup("wc"); //program: "wc" (word count)
        myargs[1] = strdup("p3.c"); //argument: file to count
        myargs[2] = NULL; //marks end of array
        execvp(myargs[0],myargs); //runs word count
        printf("this shouldn't print out");

    } else {//parent process
        // int wc = wait(NULL);
        // printf("hello, i am parent of %d (wc: %d) (pid: %d)\n", rc, wc, (int) getpid());
    }

    return 0;
}

So I have commented out the else statement (the arguments or the actions of the parent process. I was wondering what would happen, or would the outputs remain the same if the parent process does not have to wait for the child process? If so, why? 因此,我已经注释了else语句(父进程的参数或操作。我想知道会发生什么,或者如果父进程不必等待子进程,输出是否会保持不变?如果是,为什么?

I was thinking, since the child process is its own independent process from the parent, the output would remain the same but is that the only reason why? 我当时在想,由于子进程是其自己的独立于父进程的进程,因此输出将保持不变,但这是唯一的原因吗?

Some pointers would be nice, thanks! 一些指针会很好,谢谢!

This can be understood in two contexts. 这可以在两种情况下理解。

  1. Execution time of parent < execution time of child 父执行时间<子执行时间
  2. Execution time of parent > execution time of child 父母的执行时间>子女的执行时间

In case 1, the parent process exits before the child and hence, the init process (pid 1) becomes the parent of the child; 在情况1中,父进程在子进程之前退出,因此,初始化进程(pid 1)成为子进程的父进程; child process continues execution. 子进程继续执行。

Normally, a child process (resources of child process) cannot be released until the parent process completes. 通常,子进程(子进程的资源)在父进程完成之前无法释放。 In case 2, the child process is released only after the completion of parent process; 在情况2中,子进程仅在父进程完成后才被释放; till that time the child process becomes a zombie (defunct in ps -al command). 直到那个时候,子进程变成了僵尸(在ps -al命令中已ps -al )。

In this particular context, when the parent process has nothing to execute, the execution time of child > execution time of parent , which is nothing but execution time of parent < execution time of child . 在此特定上下文中,当父进程没有什么要执行时,ch​​ild执行时间> parent的执行时间 ,这就是parent的执行时间<child的执行时间 This is case 1. Hence, the parent process exits and init process becomes the parent of the child process. 这是情况1。因此,父进程退出,而init进程成为子进程的父进程。

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

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