c - 从 exec 获取输出

标签 c terminal exec fork

我正在尝试编写一个 C 程序来获取命令输出,然后将其传递给另一个程序。

我有一个问题,我不知道如何获取命令输出并存储它。以下是我所拥有的示例

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

所以基本上我想知道是否有任何方法可以从“execl”获取输出并将其传递给其他东西(例如通过将其存储在某种缓冲区中)。

建议会很好。

最佳答案

您必须使用 pipe() 创建从父进程到子进程的管道。 然后,您必须使用 dupdup2标准输出 (STDOUT_FILENO) 和错误输出 (STDERR_FILENO) 重定向到管道,并在父进程中,从管道中读取。 它应该有效。

#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;
}

关于c - 从 exec 获取输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7292642/

相关文章:

c - 了解进程的执行环境

php - 如何通过php通过exec命令行压缩

python - exec() 方法的变量在哪里定义?

linux - 在 linux 终端中查找并删除文件名中包含相同字符串的文件

c++ - 使用 Visual Studio 2008 从 x86 编译 x64 dll

c - 我如何控制其他程序?

c - C预处理器中的strlen?

c - 如何查找父进程的所有子进程(在 C 中)

linux - Bash 提示出现在输出中间