微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在fork'ed过程中的IOstream

以下示例代码将执行,但分叉进程的输出不可读:控制台上不显示任何内容,直到按Enter键,然后出现“Read Failed!”(读取失败! 显示

问题是:为什么是这样的,我怎么能与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; }

更新:

IOstream的奇怪行为的另一个例子:

Python 2.6:从Windows控制台应用程序读取数据。 (使用os.system?)

Go编译器有一个窗口设置选项吗?

在Windows上的IEx(交互式Elixir控制台)中启用UTF8字符

代码创build另一个窗口?

我怎样让我的控制台窗口出现在不同的位置?

/* 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; }

解决scheme是用vforkreplacefork 。 我只是不知道为什么这个工作…

为什么我的控制台应用程序有命令历史?

将std :: coutredirect到新创build的控制台

使用grep来searchfind所提供的文件:find有什么问题。 | xargs grep'…'?

神秘的笑脸出现在我的命令提示符下,令我感到莫名其妙,是我的代码泄漏?

Py2Exe:避免Windows请求执行.exe文件的权限

我想你想wait(2) 。 如在

/* 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,s); } } else { while (wait(&status) != pid); } return 0; }

这是因为你的子进程现在处于一个孤立的进程组中,没有进程是shell的直接子进程(谁应该做工作控制)。

孤立进程组:进程组没有至少有一个父进程组中,但在同一个会话中的父进程组 (〜是壳的直接子进程 )。

父母双方都在跑,情况就是这样的:

$ ps fax -o pid,pgid,sid,ppid,tty,stat,time,cmd 27177 27177 27177 32170 pts/6 Ss 00:00:00 | _ /bin/bash 4706 4706 27177 27177 pts/6 S+ 00:00:00 | _ ./ex1 4707 4706 27177 4706 pts/6 S+ 00:00:00 | _ ./ex1

在进程组4706上有两个进程4706和4707. 4706是27177的子进程,它在同一个进程(27177)中,但是进程组(27177)不同:它是处理进程组4706的作业控制的shell 。

父母去世时,情况是这样的:

$ ps fax -o pid,cmd 27177 27177 27177 32170 pts/6 Ss+ 00:00:00 | _ /bin/bash 4664 4663 27177 1 pts/6 S 00:00:00 ./ex1

进程组4663中只有一个进程4664,而其父进程(init)不在同一个进程中。 shell不能处理这个进程组的作业控制,因此, read()和write()会得到EIO 。

如果你在UNIX / Linux上,当stdout进入控制台时,它是行缓冲的。 也就是说,直到你做任何一个,你都看不到任何输出

fflush(stdout)

prinf("n")

标准输出缓冲区溢出。

当标准输出到其他地方(如文件管道)时,它是完全缓冲的,即printf("n")不会刷新缓冲区。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐