简体   繁体   English

确保父进程在子进程之前终止

[英]Ensuring that parent process terminates before child

If I use the following line in the child after a fork : 如果在fork后的孩子中使用以下行:

while( getppid() != 1 )

to ensure that the parent terminates before the child (as when the parent terminates, the parent of the child process becomes the init process) then what possible problems could I face, if any ? 确保父项在子项之前终止(就像父项终止时,子进程的父级成为init进程一样),那么我可能会遇到什么问题(如果有)?

Is this a good way to ensure that the child terminates after the parent ? 这是确保孩子在父母身后终止的好方法吗?

What other way is there ? 还有什么其他方式?

spin loops are never a good thing. 自旋循环从来都不是一件好事。 Open a pipe before you fork. 叉前打开管道。 Have the child block on a read. 让孩子阅读。 When the parent terminates, the pipe will close and the child will proceed. 父级终止时,管道将关闭,子级将继续。 (Make sure the child closes the write side of the pipe!) (确保孩子关闭管道的写面!)

For example: (WARNING: ALL ERROR CHECKING OMITTED) 例如:(警告:忽略所有错误检查)

int
main( void ) {
    int fd[ 2 ];
    pipe( fd );
    if( fork() ) {
        sleep( 2 );
        puts( "parent awakes" );
    } else {
        char k;
        close( fd[ 1 ]);
        read( fd[ 0 ], &k, 1 );
        puts( "child continues" );
    }
    return 0;
}

Also note that the child ought to close the read side of the pipe when it's done, but I've left that out of the sample code since it is not relevant to the problem of waiting for the parent to terminate. 还要注意,子级应该在完成后关闭管道的读取侧,但是我将其保留在示例代码之外,因为它与等待父级终止的问题无关。

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

相关问题 SIGTSTP处理程序会终止父进程和子进程 - SIGTSTP Handler terminates both parent and child process 在C语言中,如果父进程终止,那么子进程会自动终止吗? - In C, if a parent process terminates, then will the child process automatically terminate? 使用SIGTERM对子进程调用kill会终止父进程,但使用SIGKILL调用它会使父进程保持活动状态 - Calling kill on a child process with SIGTERM terminates parent process, but calling it with SIGKILL keeps the parent alive 如何在孩子完成之前杀死父进程? - How to kill parent process before the completion of the child? 在子进程之前执行父进程,反之亦然 - Execute parent process before child process or vice versa C程序子进程在父进程之前再次摩擦 - C program child process rub again before parent process 僵尸进程的父进程终止后会发生什么? - What happens after the parent of zombie process terminates? 子进程终止时了解SIGCHLD - Understanding SIGCHLD when the child process terminates 如果插入数组,程序会在子进程中提前终止 - Program terminates early in the child process if an array is inserted 创建了两个子进程。 父进程应该一直执行到一个子进程终止。 我如何在 c 中编写这个程序? - Two child process are created. The parent process should execute until one child process terminates. How do I write this program in c?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM