Write a c function that implements simple piping Example ls
Solution
What is pipe command?
The pipe command ( | ) connects two commands in such a way that output of one command becomes input to the other command. By generating system calls we can achieve this in c programming.
// Executes the pipe command: ls -al | more
#include <stdlib.h>
 #include <stdio.h>
// function declaration
 void pipefunctio(int pfd[]);
// The required commands to be executed in shell
char *command1[] = { \"ls\", \"-al\", 0 };
 char *command2[] = { \"more\", 0 };
// main method goes here
 int main()
 {
 // two int variables for status and id
    int pid, status;
 //fd[0] for command 1 produce output and fd[1] for command 2 read output of command 1
    int fd[2];
 // opening pipe
    pipe(fd);
// switch for process id pid
    switch (pid = fork()) {
   case 0: // child forck - calling function
        pipefunction(fd);
 // exit after calling
        exit(0);
   case -1:
        perror(\"fork\");
        exit(1);
 default: // parent process
        while ((pid = wait(&status)) != -1)
            fprintf(stderr, \"process %d exits with %d\ \", pid, WEXITSTATUS(status));
        break;
   
    }
    exit(0);
 }
 void pipefunction(int pfd[])
 {
    int pid;
switch (pid = fork()) {
   case 0: // child process/ fork
        dup2(pfd[0], 0);
        close(pfd[1]);   /* the child does not need this end of the pipe */
        execvp(command2[0], command2);
        perror(command2[0]);
    case -1:
        perror(\"fork\");
        exit(1);
 default: // parent process
        dup2(pfd[1], 1);
        close(pfd[0]);   /* the parent does not need this end of the pipe */
        execvp(command1[0], command1);
        perror(command1[0]);
    }
 }


