Home > Software design >  Unix redirect command programmatically
Unix redirect command programmatically

Time:11-21

I'm writing a program where I want to redirect command to another process programmatically. So if I receive the command as argument, I want to receive the output on the parent process.

My code is:

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>

int main(int argc, char* argv[]) {
{ 
    char msg[8]=“message”;
    int pp[2];
    if(pipe(pp)<0) {
        printf("Error pipe");
        exit(1);
    }
    if (!fork())
    { 
        close(fd[0]);
        
        //TODO...

    } else { 
        close(fd[1]);
        read(fd[0], msg, 8);
        close(fd[0]);
    }
} 

I'm lost about the child part, where I execute the command and do the redirection. I'm using pipe to communicate between child process and parent process.

On the child side, I've closed the pipe side not used, then I don't know how to continue.

Can you help?

CodePudding user response:

The steps are the following:

  1. close pipe-read and stdout
  2. dup() pipe-write to redirect pipe-write to stdout with fd=1
  3. close initial pipe-write
  4. execute the command, reading from argv the first argument

Your code becomes like that:

if (!fork())
{ 
    close(pp[0]);
    close(1);
    dup(pp[1]);
    close(pp[1]);
    execlp(argv[1], argv[1],(char *)0); 
    exit(0)
}
  • Related