[英]waitpid not returning after child has exited
使用相當標准的fork過程:
int pipe_to_child[2];
int pipe_from_child[2];
int child_exit_status = -1;
pid_t child_pid = fork();
if (child_pid == 0) {
close(pipe_from_child[0]); // close their read end
close(pipe_to_child[1]); // Close their write end
dup2(pipe_to_child[0], STDIN_FILENO); // Tie the in pipe to stdin
dup2(pipe_from_child[1], STDOUT_FILENO); // Tie stdout to the out pipe
// Run the child process
execve(file_to_run, argv_for_prog, env_for_prog);
}
else {
close(pipe_from_child[1]); // close their write end
close(pipe_to_child[0]); // Close their read end
if (input_to_prog != NULL) write(pipe_to_child[1], input_to_prog, strlen(input_to_prog)); // Send the stdin stuff
close(pipe_to_child[1]); // Done so send EOF
// Wait for the child to end
waitpid(child_pid, &child_exit_status, 0);
// Do post end-of-child stuff
}
這通常按預期工作。
但是,當子進程(shell腳本)在后台啟動另一個進程時。 即使子進程隨后退出(並且不再由ps
列出),waitpid也不會返回。
這種情況下的腳本旨在啟動在后台運行的inadyn-mt(DDNS更新程序)。
#!/bin/sh
inadyn-mt --background
(如果我在inadyn-mt之后加上&,則沒有區別)
事實證明,問題在於管道沒有關閉。 盡管子進程退出正常,但由於它已生成了一個進一步的進程,因此,該進程(即使不希望它們)也綁定到子級stdin和stdout的管道。 我使用的解決方案是,當我要從一個孩子中分出一個孩子時,不設置管道。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.