将命令的输出作为C中另一个命令的输入

时间:2016-04-27 19:53:12

标签: c command pipe

所以,我有这个命令行,我想用C:

执行
ps -eo user,pid,ppid 2> log.txt | grep user 2>>log.txt | sort -nk2 > out.txt

我需要弄清楚我是如何制作代码的...... fd 我的理解是我有父亲ps ...哪个需要将输出重定向为grep的输入,并且还需要将输出错误输出到log.txt ......

与grep相同...必须将输出重定向到排序,并且必须将错误保存在log.txt中。

我只是将排序输出到文件......

这样的事情:

FATHER(ps)               SON(grep)         SON-SON? (sort)

0->must be closed  ----> 0           ----> 0
                  /                 /
1 ---------------/       1 --------/       1 -->out.txt

2 ---> log.txt           2 ---> log.txt    2 -->nowhere?

但我不知道这是如何编码的...... 我很感激你的帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用sh -c

直接在C程序中执行shell命令

How do I execute a Shell built-in command with a C function?

管道也可以直接使用popen()

在C程序中使用

以下程序示例显示如何将ps -A命令的输出传递给grep init命令:ps -A | grep init

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

int
main ()
{
  FILE *ps_pipe;
  FILE *grep_pipe;

  int bytes_read;
  int nbytes = 100;
  char *my_string;

  /* Open our two pipes */
  ps_pipe = popen ("ps -A", "r");
  grep_pipe = popen ("grep init", "w");

  /* Check that pipes are non-null, therefore open */
  if ((!ps_pipe) || (!grep_pipe))
    {
      fprintf (stderr,
               "One or both pipes failed.\n");
      return EXIT_FAILURE;
    }

  /* Read from ps_pipe until two newlines */
  my_string = (char *) malloc (nbytes + 1);
  bytes_read = getdelim (&my_string, &nbytes, "\n\n", ps_pipe);

  /* Close ps_pipe, checking for errors */
  if (pclose (ps_pipe) != 0)
    {
      fprintf (stderr,
               "Could not run 'ps', or other error.\n");
    }

  /* Send output of 'ps -A' to 'grep init', with two newlines */
  fprintf (grep_pipe, "%s\n\n", my_string);

  /* Close grep_pipe, checking for errors */
  if (pclose (grep_pipe) != 0)
    {
      fprintf (stderr,
               "Could not run 'grep', or other error.\n");
    }

  /* Exit! */
  return 0;
}

来源http://crasseux.com/books/ctutorial/Programming-with-pipes.html

否则使用命名管道https://en.wikipedia.org/wiki/Named_pipehttp://www.cs.fredonia.edu/zubairi/s2k2/csit431/more_pipes.html

另请参阅此C program to perform a pipe on three commands(使用fork()