【发布时间】:2014-02-15 05:21:55
【问题描述】:
通过函数execvp() fork 并执行子程序后,父进程退出。但是这会导致子进程中的函数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
【问题讨论】: