Search code examples
clinuxdup2

redirection using dup2 command


I know this is a simple exercise but I'm having troubles with it.

 ps | sed 1d | wc -l

I am trying to generate an output of the above terminal command using c code for my school exercise. I have written a code that is redirecting all the inputs and outputs to the required destination but I am not getting any output on the console as I haven't redirected the final output in any file so it must be displayed on console.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/file.h>  
#define READ 0
#define WRITE 1
int main()
{
   //fd       fd1
//ps | sed 1d | wc -l 
pid_t pid;
pid_t pid1;
pid_t pid2;
int fd[2];
int fd1[2];
pipe(fd);
pipe(fd1);
pid=fork();
if(pid==0)
{                          //redirecting into sed 1d
    close(fd[READ]);
    dup2(fd[WRITE],1);
    close(fd[WRITE]);
    execlp("ps","ps",NULL);
}
else
{
    pid1=fork();
    if(pid1==0)
    {                          //redirecting into wc -l
        close(fd[WRITE]);
        dup2(fd[READ],0);
        close(fd[READ]);
        close(fd1[READ]);
        dup2(fd1[WRITE],1);
        close(fd1[WRITE]);
        execlp("sed","sed","1d",NULL);
    }
    else
    {
        pid2=fork();
        if(pid2==0)
        {                          //must display on console
            close(fd1[WRITE]);
            dup2(fd1[READ],0);
            close(fd1[READ]);
            execlp("wc","wc","-l",NULL);
        }
        
        else
        
        {
            close(fd[READ]);
            close(fd[WRITE]);
            close(fd1[READ]);
            close(fd1[WRITE]);
            wait(NULL);
        }
        
    }
    
}

}

What can be the problem?


Solution

  • The ps process has both ends of the fd1 pipe open, which it shouldn't. Also, the wc -l process has both ends of the fd pipe open, which it shouldn't. Fix both of those things and your program will stop hanging. Also, wait(NULL) only waits for one child process to terminate, not all of them, so you're risking the terminal prompt reappearing before your program is actually done.