简体   繁体   中英

Piping the output of a command as an input of another in C

So, I have this command line I want to execute in C:

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

And I need to figure out how I'd make the code... fd What I understand is that I have the father ps... Which needs to redirect the output as an input to the grep, and it also needs to error output to log.txt...

The same with the grep... the output must be redirected to the sort, and the error must be saved in log.txt.

and I'd just output the sort to the file...

Something like this:

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?

But I don't know how this would be coded... I'd appreciate your help.

You can execute shell commands in C programs directly using sh -c

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

Pipes can also be used in C programs directly using popen()

The following program example shows how to pipe the output of the ps -A command to the grep init command: 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;
}

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

else use named pipes ( https://en.wikipedia.org/wiki/Named_pipe ) http://www.cs.fredonia.edu/zubairi/s2k2/csit431/more_pipes.html

See also this C program to perform a pipe on three commands (uses fork() )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM