Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement piping ("|") using C..(fork used)

Tags:

c

fork

gcc

pipe

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

int main(int argc,char **argv)
{
    int fd[2];
    pid_t childpid;
    pipe(fd);
    childpid=fork();
    if (childpid == -1)
    {
        perror("Error forking...");
        exit(1);
    }
    if (childpid)   /*parent proces*/   //grep .c
    {
        wait(&childpid);        //waits till the child send output to pipe
        close(fd[1]);
        close(0);       //stdin closed
        dup2(fd[0],0);
        execlp(argv[2],argv[2],argv[3],NULL);

    }
    if (childpid==0)  //ls
    {
        close(fd[0]);   /*Closes read side of pipe*/
        close(1);       //STDOUT closed
        dup2(fd[1],1);
        execl(argv[1],NULL);
    }
    return 0;
}

If i give command line argument as "ls grep .c" i should get all the ".c" files displayed.

Pseudocode:- My child process will run "ls" & parent process will run "grep .c".. Parent process waits till the child process completes so that child writes to the pipe.

Test run:-

bash-3.1$ ls | grep .c
1.c
hello.c
bash-3.1$ ./a.out ls grep .c
bash-3.1$

Why is that happening?

like image 335
Abhijeet Rastogi Avatar asked Feb 03 '10 11:02

Abhijeet Rastogi


People also ask

What are pipes used for in C?

A pipe is a system call that creates a unidirectional communication link between two file descriptors. The pipe system call is called with a pointer to an array of two integers. Upon return, the first element of the array contains the file descriptor that corresponds to the output of the pipe (stuff to be read).

What is C fork?

Fork system call is used for creating a new process, which is called child process, which runs concurrently with the process that makes the fork() call (parent process). After a new child process is created, both processes will execute the next instruction following the fork() system call.

What is fork pipe?

fork() − it creates a child process, this child process ahs a new PID and PPID. pipe() is a Unix, Linux system call that is used for inter-process communication.

How pipes are created and used in IPC with examples?

A pipe file is created using the pipe system call. A pipe has an input end and an output end. One can write into a pipe from input end and read from the output end. A pipe descriptor, has an array that stores two pointers, one pointer is for its input end and the other pointer is for its output end.


2 Answers

A simple mistake: your execl call should actually be execlp. Besides, you can get rid of the wait and close statements. Then you should check the error code of execlp.

like image 81
user231967 Avatar answered Nov 05 '22 01:11

user231967


One more thing, the close(0) and close(1) are unnecessary, the dup2() function automatically does that for you.

like image 24
sud03r Avatar answered Nov 05 '22 01:11

sud03r