打开一个cmd程序的全部功能(I / O) [英] Open a cmd program with full functionality (i/o)
问题描述
我试过的popen()
和它运作良好的输出R
作为第二个参数传递;我知道你可以使用W
写作模式,它为我工作(该方案是只有一个 scanf()的
)。我的问题是如何使用append(一
)模式。你既可以写和读,你怎么知道什么时候该程序输出的东西,当它要求用户输入?
I tried popen()
and it is working well for output with "r"
passed as a second argument; I know you can use "w"
as writing mode and it worked for me (the program was just one scanf()
). My question is how to use the append ("a"
) mode. You can both write and read, how do you know when the program is outputting something and when it's requesting for user input?
推荐答案
的popen使用的管道(这是P中的popen)和管道是单向的。可以读取或从管的一端,而不是两个写。两者都要读/写访问,你应该使用socketpair来代替。我用这个在我的计划时,我想是这样的popen,但读/写:
popen uses a pipe (that's the "p" in "popen") and pipes are unidirectional. You can either read or write from one end of a pipe, not both. To get both read/write access you should use a socketpair instead. I use this in my programs when I want something like popen, but for read/write:
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <unistd.h>
FILE *sopen(const char *program)
{
int fds[2];
pid_t pid;
if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) < 0)
return NULL;
switch(pid=vfork()) {
case -1: /* Error */
close(fds[0]);
close(fds[1]);
return NULL;
case 0: /* child */
close(fds[0]);
dup2(fds[1], 0);
dup2(fds[1], 1);
close(fds[1]);
execl("/bin/sh", "sh", "-c", program, NULL);
_exit(127);
}
/* parent */
close(fds[1]);
return fdopen(fds[0], "r+");
}
请注意,由于它不返回孩子的PID,你有小孩程序退出后,一个僵尸进程。 (除非你设置SIGCHLD ...)
Note that since it doesn't return the child's pid, you'll have a a zombie process after the child program exits. (Unless you set up SIGCHLD...)
这篇关于打开一个cmd程序的全部功能(I / O)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!