popen方法并发读取和写入 [英] popen simultaneous read and write

查看:812
本文介绍了popen方法并发读取和写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以读取和写入由popen这返回的文件描述符。我有一个互动的过程,我想通过C.控制如果这是不可能的的popen,有周围没有任何办法?

Is it possible to read and write to a file descriptor returned by popen. I have an interactive process I'd like to control through C. If this isn't possible with popen, is there any way around it?

推荐答案

前面已经回答了,popen这工作的一个方向。如果你需要读取和写入,您可以创建管道()管道,通过跨越叉一个新的进程()和exec函数,然后重定向其输入和输出dup2()。无论如何,我美元,popen这p $ PFER EXEC,因为它使您能够处理(例如你知道它的PID)

As already answered, popen works in one direction. If you need to read and write, You can create a pipe with pipe(), span a new process by fork() and exec functions and then redirect its input and outputs with dup2(). Anyway I prefer exec over popen, as it gives you better control over the process (e.g. you know its pid)

打开进程,重定向其输入和输出看起来基本上是这样的(我没有这个编制,但是这仅仅是想法):

Opening a process and redirecting its input and output would look basically like this (I haven't compiled this, but this is just the idea):

pid_t pid = NULL;
int pipefd[2];
FILE* output;
char buf[256];

pipe(pipefd);
pid = fork();
if (pid == 0)
{
// Child
  dup2(pipefd[0], STDIN_FILENO);
  dup2(pipefd[1], STDOUT_FILENO);
  dup2(pipefd[1], STDERR_FILENO);
  execl("your/script", "/path/to/your/script", (char*) NULL);
  // Nothing below this line should be executed by child process. If so, 
  // it means that the execl function wasn't successfull, so lets exit:
  exit(1);
}
// The code below will be executed only by parent. You can write and read
// from the child using pipefd descriptors, and you can send signals to 
// the process using its pid by kill() function. If the child process will
// exit unexpectedly, the parent process will obtain SIGCHLD signal that
// can be handled (e.g. you can respawn the child process).

// Now, you can write to the process using pipefd[0], and read from pipefd[1]:

write(pipefd[0], "message", strlen("message")); // write message to the process
read(pipefd[1], buf, sizeof(buf)); // read from the process. Note that this will catch 
                                   // standard  output together with error output
kill(pid, signo); //send signo signal to the child process

这篇关于popen方法并发读取和写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆