执行以下代码示例,但分叉进程的输出不可读:控制台上没有显示任何内容,直到按Enter键,然后出现“Read failed!”显示。fork()'ed进程中的IO流
现在的问题是:为什么是这样的,我怎样才能与fork()
编辑过程中的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;
}
的解决方案是与vfork
更换fork
。我只是不知道为什么这个工作正常...
也许是因为父母在孩子完成之前退出? – 2011-07-29 11:45:12
@ 0A0D:谢谢,这似乎是这种情况,并且可以通过使用'system()'调用而不是'fork' /'execv'来轻松解决问题。但是,如何在继承IO流的单独进程中启动可执行文件?我的意思是,我需要能够随时杀死父进程,而不必等待孩子退出。 – Andy
@Andy - 'vfork'暂停调用过程,直到孩子终止。这与在父进程中调用“wait”完全相同。 – Seth