问题描述
我正在尝试与外部程序通信,如果执行该程序,将运行终端界面。 通常我必须提供一些输入(例如“1+1”),然后读取程序的输出(例如“2”)。 由于我需要双向通信,因此无法使用 popen()。
我的问题如下:
每当我有一部分代码要求输入时,例如包含 std::cin >> input
,我都会遇到同样的问题,read
命令永远不会退出。
这里我写了一个最小的例子,子进程所做的就是读取输入并重复它。
当我尝试运行此代码时,我看到第一个打印“Parent said:”并且我可以提供输入并使用 write
发送它。但是,当我再次尝试调用 read()
函数以查看结果时,它永远不会退出。
我注意到,如果我关闭从父级到子级 (fd_p2c[1]
) 的管道,那么我可以成功读取。
这显然不是我想要的,因为在我的应用程序中,我希望两个通信都保持开放。
有什么建议可以解决这个问题吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/prctl.h>
#include <sys/wait.h>
#include <unistd.h>
int main() {
int status,buf_length;
// Input and output
char buf[256];
char msg[256];
char child_read[256];
int fd_c2p[2]; // file descriptor pipe child -> parent
int fd_p2c[2]; // file descriptor pipe parent -> child
pipe(fd_c2p);
pipe(fd_p2c);
// Spawn a new process with pid
pid_t pid = fork(); // Fork process
if (pid == 0) {
// Child
// Close the unused end of the pipe
if (close(fd_p2c[1]) != 0 || close(fd_c2p[0]) != 0) {
fprintf(stderr,"Faild to close unused end of pipe\n");
exit(1);
}
// Set the comunication
if (dup2(fd_p2c[0],STDIN_FILENO) != 0 ||
dup2(fd_c2p[1],STDOUT_FILENO) != 1 ||
dup2(fd_c2p[1],STDERR_FILENO) != 2) {
fprintf(stderr,"Faild to duplicate the end of the pipes\n");
exit(1);
}
// These two pipe ends are not needed anymore
if (close(fd_p2c[0]) != 0 || close(fd_c2p[1]) != 0) {
fprintf(stderr,"Faild to close unused end of pipe\n");
exit(1);
}
// ask kernel to deliver SIGTERM in case the parent dies
prctl(PR_SET_PDEATHSIG,SIGTERM);
// Moch program
while (1) {
fprintf(stdout,"Parent says: ");
fflush(stdout);
scanf("%s",child_read);
fprintf(stdout," >> Child repeat: %s\n",child_read);
fflush(stdout);
}
exit(1);
} else {
// Parent
// These two pipe ends are not needed anymore
if (close(fd_p2c[0]) != 0 || close(fd_c2p[1]) != 0) {
fprintf(stderr,"Faild to close unused end of pipe\n");
exit(1);
}
}
// Read output and send input
while (1) {
// Read from child
while (buf_length = read(fd_c2p[0],buf,sizeof(buf) - 1)) {
buf[buf_length] = '\0';
printf("%s",buf);
}
// Enter message to send
scanf("%s",msg);
if (strcmp(msg,"exit") == 0)
break;
// Send to child
write(fd_p2c[1],msg,strlen(msg));
//close(fd_p2c[1]);
}
printf("KILL");
kill(pid,SIGKILL); // send SIGKILL signal to the child process
waitpid(pid,&status,0);
}
解决方法
一个问题是在子进程中:
scanf("%s",child_read);
对于 %s
格式,只有三件事可以阻止 scanf
等待更多输入:
- 错误
- 文件结束
- 空间
假设一切正常,就不会有错误。并且由于父进程使管道保持打开状态,因此文件不会结束。而且由于父进程只写入它自己用 scanf("%s",...)
读取的内容,因此发送的数据中不会有空格。
总而言之,子进程将无限期地等待 scanf
返回,而它永远不会。
如果您需要双向通信,您可以使用一些 unix(7) 套接字,或者 几个 pipe(7)-s,或者一些 fifo(7)。>
您可以使用一些 JSONRPC 库。或 XDR(可能是 ONC/RPC/XDR)或 ASN/1 用于数据中心异构计算机之间的二进制通信,或 MPI。如果您可以使用一些 supercomputer,它可能具有专有库来简化在不同节点上运行的进程之间的消息传递。
考虑使用 OpenMPI。
我正在尝试与外部程序通信,如果执行该程序,将运行终端界面。
也许你需要一些带有 pty(7) 的 termios(3) ?然后从 xterm
或 rxvt
在尝试 event loop(或 poll(2)...)或 read(2)(或 recv(2) 之前,您可能需要一些 write(2) }})
您可以找到开源库(例如 send(2)、Glib、...)来帮助您,您当然应该研究它们的源代码以获得灵感。
,让我们称一个词是scanf("%s")
能够提取的内容。
这是不是分隔符的连续字符序列(空格、制表符、换行符...)。
孩子的(重定向的)标准输入读取带有scanf("%s",child_read);
的单词。
当读取分隔符或到达 EOF 时,这个 单词 被称为结束。
在父级中,write(fd_p2c[1],msg,strlen(msg));
发送一个 word(后面没有其他内容),因为 msg
在之前被提取为 word。 >
请注意,当您使用键盘输入 word 时,您还按下了 Enter 键,这会在标准输入中发送换行符。此时,终端使此行可用于 scanf()
,word 被称为已结束并且分隔符被忽略(在这种特定情况下,但我们可以通过 {{1 }}).
例如,如果在父级的标准输入中我们输入fgetc()
,
父级获得单词 "abc\n"
,它按原样发送给子级。
然后孩子收到一个以 "abc"
开头但还没有结束的词:"abc"
仍在等待 scanf("%s")
之后的一些其他字符使这个词更长,或者一个分隔符或 EOF 来检测结束这个词。
例如,您可以在这个词之后发送一个分隔符。
c
或者最好依靠 // Send to child
write(fd_p2c[1],strlen(msg));
char lf='\n';
write(fd_p2c[1],&lf,1);
(而不是 fgets()
)在子级和父级中获取一行(不仅仅是一个单词)。
顺便说一下,父级中的 scanf("%s")
对我来说看起来很奇怪。
我会做这样的事情。
while/read
,
因为一般来说,我不知道消息的长度,因为我需要阅读 getValue()
表格,所以我需要创建一个外观来监听管道直到它为空。
如@some-programmer-dude 所建议的那样,有必要将 fd_c2p
添加到父文件描述符中:
O_NONBLOCK
现在,当我从文件描述符 // Parent
// close unused pipe ends
// These two pipe ends are not needed anymore
if (close(fd_p2c[0]) != 0 || close(fd_c2p[1]) != 0) {
fprintf(stderr,"Faild to close unused end of pipe\n");
exit(1);
}
// Add O_NONBLOCK the the fd that reads from the child
int c2p_flags = fcntl(fd_c2p[0],F_GETFL);
fcntl(fd_c2p[0],F_SETFL,c2p_flags | O_NONBLOCK);
中读取子级的输出时,每当我们尝试从空文件中读取时,它都会返回一个错误。
读取 fd_c2p[0]
中的错误代码应与 errno
匹配。
要知道何时停止读取 EWOULDBLOCK
需要一些有关输出的知识。
当该行的最后一个字符到达 fd_c2p[0]
且上一条消息以 EWOULDBLOCK
结束时,此特定读取应停止。
:
这个补丁解决了在程序要求输入之前不确定有多少行时从文件中读取的问题。
当消息在任何位置包含 // Read from child
end_of_message = false;
while (1) {
buf_length = read(fd_c2p[0],buf,sizeof(buf) - 1);
if (buf_length == -1)
{
if (end_of_message && errno == EWOULDBLOCK)
break;
else if (errno == EWOULDBLOCK)
continue;
else {
fprintf(stderr,"reading from pd_c2p returned an error different "
"from `EWOULDBLOCK'\n");
exit(errno);
}
}
buf[buf_length] = '\0';
printf("%s",buf);
end_of_message = buf[buf_length - 1] == ':';
}
时也应该是安全的。为了测试它,可以将不同的缓冲区减少到更小的大小(例如从 256 到 1)。
@prog-fh 还指出,原则上人们希望输入也包含空格。容纳可以使用:
代替fgets
:
scanf
使用 // Enter message and send it over to the chid process
while (fgets(msg,256,stdin) != NULL) {
if (msg[strlen(msg)] == '\0')
write(fd_p2c[1],strlen(msg));
else {
fprintf(stderr,"Error encounter while reading input\n");
exit(1);
}
if (msg[strlen(msg) - 1] == '\n')
break;
else
continue;
}
的优点之一是字符串将在末尾保留换行符 fgets
,这意味着一旦我们已完成阅读邮件。
然后是完整的代码
\n