LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Piping output between processes. C. (https://www.linuxquestions.org/questions/programming-9/piping-output-between-processes-c-501041/)

banan 11-12-2006 10:58 PM

Piping output between processes. C.
 
Hello everyone. I have a problem.
I have to write a peace of code in C that will simulate a simple shell and in that shell only commands that are listed in specification file are allowed. However, that is not a problem, because I got it working already for single command entries. What I'm struggling with is geting output piped from one command to another like:
# ls -l | grep stuff
given that both ls and grep are permitted.
Any idea how to approach it?
I use fork() and execvp() to execute commands.
Many thanks in advance.

banan 11-12-2006 11:25 PM

I am so sorry.
I should have searched this forum before posting my question.
This problem can easily be solved by using popen() like it was suggested in thread below.
Sort of:
Code:

/*****************************************************************************
 Excerpt from "Linux Programmer's Guide - Chapter 6"
 (C)opyright 1994-1995, Scott Burkett
 *****************************************************************************
 MODULE: popen2.c
 *****************************************************************************/

#include <stdio.h>

int main(void)
{
        FILE *pipein_fp, *pipeout_fp;
        char readbuf[80];

        /* Create one way pipe line with call to popen() */
        if (( pipein_fp = popen("ls", "r")) == NULL)
        {
                perror("popen");
                exit(1);
        }

        /* Create one way pipe line with call to popen() */
        if (( pipeout_fp = popen("sort", "w")) == NULL)
        {
                perror("popen");
                exit(1);
        }

        /* Processing loop */
        while(fgets(readbuf, 80, pipein_fp))
                fputs(readbuf, pipeout_fp);

        /* Close the pipes */
        pclose(pipein_fp);
        pclose(pipeout_fp);

        return(0);
}

Sorry ones again.


All times are GMT -5. The time now is 09:25 PM.