IO流在fork()的ed进程中
The following example code executes, but output from the forked process is not readable: nothing is shown on console until I press enter, and then "Read failed!" shows.
下面的示例代码执行,但是来自分叉进程的输出不可读:在我按enter之前,控制台上没有显示任何内容,然后显示“Read failed!”
The question is: why is that, and how can I interact with stdin
and stdout
from the fork()
'ed process?
问题是:为什么会这样,以及如何从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;
}
Update:
更新:
Another example of strange behavior of IO streams:
另一个关于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
script:
的回声。sh脚本:
#!/bin/sh
read -p "Enter something: " INPUT
echo "You entered $INPUT"
This one returns
这一个回报
Enter something: /home/user/echo.sh: line 3: read: read error: 0: Input/output error
You entered
Update 2:
更新2:
Looks like this code does exactly what's needed:
看起来这段代码所做的正是我们所需要的:
#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;
}
The solution was to replace fork
with vfork
. I just don't know why is this one working...
解决方案是用vfork替换fork。我只是不知道为什么这个工作…
3 个解决方案
#1
2
I think you want wait(2)
. As in
我想你需要等一下。就像在
/* example1.c */
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
int main() {
int status;
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);
}
}
else
{
while (wait(&status) != pid);
}
return 0;
}
更多相关文章
- 自己实现的C++智能指针的功能代码和测试用例
- Linux 下 Sublime Text 3 安装 Godef 进行代码跳转/跳回
- Linux 上传代码到github
- Media-S 简介(一个开源的DRM解决方案)
- linux 下使用 vim+cscope+ctags+taglist+NERDtree实现代码阅读编
- 如何查看linux命令源代码和函数源代码
- UNIX网络编程之源代码的编译和使用
- mt7620的u-boot 代码
- 在arcpy中删除或删除表的代码是什么?