【发布时间】:2011-07-29 10:58:29
【问题描述】:
以下示例代码执行,但分叉进程的输出不可读:在我按 Enter 之前,控制台上没有显示任何内容,然后“读取失败!”显示。
问题是:为什么会这样,我如何通过fork()'ed 进程与stdin 和stdout 交互?
/* example1.c */
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
int main() {
pid_t pid = fork();
if (!pid) {
// child
char s[64];
printf("Enter something: ");
char *res = fgets(s, 64, stdin);
if (!res) {
printf("Read failed!\n");
} else {
printf("You entered: %s", s);
}
}
return 0;
}
更新:
IO 流异常行为的另一个例子:
/* example2.c */
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
int main() {
pid_t pid = fork();
if (!pid) {
// child
char *argv[] = {
"-c",
"/home/user/echo.sh",
NULL
};
execv("/bin/sh", argv);
}
return 0;
}
echo.sh脚本:
#!/bin/sh
read -p "Enter something: " INPUT
echo "You entered $INPUT"
这个返回
Enter something: /home/user/echo.sh: line 3: read: read error: 0: Input/output error
You entered
更新 2:
看起来这段代码完全符合我们的需要:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
int main() {
pid_t pid = vfork();
if (!pid) {
// child
system("/home/user/echo.sh");
}
return 0;
}
解决方案是将fork 替换为vfork。我只是不知道为什么这个工作......
【问题讨论】:
-
可能是因为父母在孩子完成之前就退出了?
-
@0A0D:谢谢,似乎是这样,使用
system()调用而不是fork/execv可以轻松解决问题。但是如何在继承 IO 流的单独进程中启动可执行文件?我的意思是,我需要能够随时终止父进程,而无需等待子进程退出。 -
@Andy -
vfork暂停调用进程,直到子进程终止。这和在父进程中调用wait完全一样。 -
虽然
vfork()在当前 Linux 上挂起父级直到子级退出或执行,但不能保证这样做,事实上已经有 vfork 的实现是#define vfork fork。