简体   繁体   English

父进程不等待子进程(C代码)

[英]parent process does not wait for the child process (c code)

char array[ARRAY_SIZE];

void child_process_routine(){
int j;
    for(j = 0;j<ARRAY_SIZE;j++)
    array[j]='d';
}

main()
{
    pid_t child_pid;
    int i;
    for(i = 0;i<ARRAY_SIZE;i++)
    array[i]='c';
    child_pid = fork();

        switch (child_pid) {
        case -1:
            perror("error");    
            exit(1);
        case 0: 
            child_process_routine();
            exit(0);    
        default:
            wait(NULL);
        }

    print_array(array); 
}

can you explain me why the parent process does not wait for the child process and this gives me the output " cccccc " again? 您能解释一下为什么父进程不等待子进程,而这又使我输出“ cccccc”吗? it was changed in the child process into " dddddd " 在子进程中将其更改为“ dddddd”

what does wait(NULL) even do? wait(NULL)还能做什么?

how does it supposed to know it should wait for the child process? 它应该如何知道它应该等待子进程?

The parent process is waiting for the child process. 父进程正在等待子进程。

The child is not a thread, it is a completely different process with its own unique PID and the parent as its Parent PID. 子进程不是线程,它是一个完全不同的进程,具有自己的唯一PID和父进程作为其父进程PID。 The child and the parent do not share the same array, the child has its own copy since it is a different process (not a thread of the same process). 子级和父级不共享相同的数组,子级拥有自己的副本,因为它是一个不同的进程(不是同一进程的线程)。 So when you set the array to 'd' in the child it does not affect the array in the parent process. 因此,当您在子级中将数组设置为“ d”时,它不会影响父进程中的数组。

Try putting a sleep(20) in the child process flow right before it exits, and a printf() just before the parent wait(). 尝试在子进程流退出之前将sleep(20)放在子进程流中,在父进程wait()之前放入printf()。 You will see that your application pauses as the parent is waiting for the child to finish. 您将看到您的应用程序暂停,因为父母正在等待孩子完成。

fork() creates a different process but parent share the same process context. fork()创建一个不同的进程,但父进程共享相同的进程上下文。

but if you try to change anything in the stack segment of parent it makes a copy of that and creates a separate stack for child process, but all the resources like data segment, code segment, etc are not copied for child process. 但是,如果您尝试更改父级堆栈段中的任何内容,则会对其进行复制并为子进程创建一个单独的堆栈,但是不会为子进程复制所有资源(如数据段,代码段等)。 They both share it. 他们俩都分享。

This copying on changing the data after fork is called "copy on write" 在fork之后更改数据的这种复制称为“写入时复制”

Parent process is waiting for child process to finish. 父进程正在等待子进程完成。 But its printig for both parent and child separately and different data for both 但是它的printig分别用于父母和孩子,并且两者的数据不同

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

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