使用execvp()
函数分叉并执行子进程后,父进程退出。然而这会导致子进程中的fgets()
函数立即返回,而不等待从stdin
输入。
我猜测父进程的退出会向子进程发送一些信号,导致fgets()
函数返回。有人能为我解释更多吗?
子进程的代码:
/* cc child.c -o child */
int main () {
char buffer[10];
fgets(buffer, 10, stdin);
printf("This is what child program read:\n%s", buffer);
}
母程序代码:
/* cc parent.c -o parent */
int main (int argc, char **argv) {
pid_t pid = fork();
if (pid < 0) {
perror("fork");
exit(EXIT_FAILURE);
}
else if (pid == 0) {
execvp(*(argv+1), argv+1);
}
else {
// while(1); if while(1) or wait() is used, child process can wait for input
exit(1);
}
}
在zsh shell中:
zsh>: ./parent ./child
zsh>: This is what child program read: // read nothing and print nothing
ps
来检查这一点。 - jdigital