[英]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.