c - dup2 - Creating a piping program -
i write program replicate functionality of
program1 | program | programx
so redirect programx's output programx+1's input.
for sake of simplicity, start off 2 programs , single pipe.
in pseudocode, approach looks this:
1. create pipe communication between child1 , child2 2. fork parent create child1 , fork parent again create child2 3. close unneeded pipe ends in children 4. redirect output of execvp() child 1 write-end of pipe via dup2, child2 receives whatever program puts out 5. child2 reads pipe , receives output program of child1 6. execute execvp() received data
so far good, here have:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #define read 0 #define write 1 int main(int argc, const char * argv[]) { //create unidirectional pipe int apipe[2]; if(pipe(apipe)){ perror("pipe call"); exit(exit_failure); } //create child 1 ("sender") pid_t child_pid = fork(); if(child_pid < (pid_t)0) { perror("fork call failed"); exit(exit_failure); } else if(child_pid == (pid_t) 0){ //in child1 close(apipe[read]); //get actual arguments argv array const char **realargs = malloc(sizeof(char *) * (argc-1)); for(int i=1;i<argc;i++){ realargs[i-1] = argv[i]; } //redirect standard output write-end of pipe dup2(apipe[write], stdout_fileno); close(apipe[write]); execvp(argv[0], realargs); //exec call failed exit(exit_failure); } //parent //create second child ("receiver") pid_t child2_pid = fork(); if(child2_pid == (pid_t)0){ //close unneeded pipe end close(apipe[write]); char buffer[1024]; char **argv2 = malloc(sizeof(char *)); while (read(apipe[read], buffer, sizeof(buffer)) != 0) { argv2[0] = buffer; printf("buffer = %s", buffer); //execvp("sort", argv2); } close(apipe[read]); exit(exit_success); } //close unneeded pipe ends, parent not need pipe close(apipe[write]); close(apipe[read]); exit(exit_success); return 0; }
that achieves trying do, output in child2 seems write pipe again , results in writing own pipe. think, , may wrong here, (despite closing write end in child2) via printf writes own pipe (as redirected stdout write end of pipe) , reads again. output looks this
when run program parameters who
, sort
myprog sort
i following output:
buffer = buffer = martine****** console apr 24 12:59
edit:
how set input sort command in execvp("sort", argsarr); ? sort takes in filename, how go ?
Comments
Post a Comment