从拼抢输出EXEC [英] Grabbing output from exec

查看:121
本文介绍了从拼抢输出EXEC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我尝试写一些东西,需要抢命令输出,然后生病治疗是它,然后将它传递到另一个程序。

so im trying to write some thing that needs to grab command output and then ill be treating it and then passing it to another program.

但有一个问题IM,我不能工作,如何获得命令的输出,并将其存储
下面是我所拥有的样本

but im having an issue, i cant work out how to get the command output and store it below is a sample of what i have

if(fork() == 0){
   execl("/bin/ls", "ls", "-1", (char *)0);
   /* hopefully do something with the output here*/
}else{
  *other stuff goes here*
 }`

所以基本上我想知道是否有什么办法可以从execl的输出和(例如,通过将它存储在某种缓冲),它传递给一些其他的东西。

so basically im wondering if there is any way i can get the output from the "execl" and pass it to some thing else (e.g. via storing it in some kind of buffer).

任何建议将是巨大的。感谢家伙..`

any suggestions would be great. thanks guys.. `

推荐答案

您必须创建从父进程的管道孩子,使用管道()
然后,你必须重定向标准输出(STDOUT_FILENO)和错误输出(STDERR_FILENO)使用 DUP dup2 来管,而在父进程,从管道中读取。
它应该工作。

You have to create a pipe from the parent process to the child, using pipe(). Then you must redirect standard ouput (STDOUT_FILENO) and error output (STDERR_FILENO) using dup or dup2 to the pipe, and in the parent process, read from the pipe. It should work.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define die(e) do { fprintf(stderr, "%s\n", e); exit(EXIT_FAILURE); } while (0);

int main() {
  int link[2];
  pid_t pid;
  char foo[4096];

  if (pipe(link)==-1)
    die("pipe");

  if ((pid = fork()) == -1)
    die("fork");

  if(pid == 0) {

    dup2 (link[1], STDOUT_FILENO);
    close(link[0]);
    close(link[1]);
    execl("/bin/ls", "ls", "-1", (char *)0);
    die("execl");

  } else {

    close(link[1]);
    int nbytes = read(link[0], foo, sizeof(foo));
    printf("Output: (%.*s)\n", nbytes, foo);
    wait(NULL);

  }
  return 0;
}

这篇关于从拼抢输出EXEC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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