-2

How would I use the dup2() and pipe() functions to commit a redirect of the output of ls into the input of wc. Therefore printing the word count.

here is my attempt, however this is not working.

 if(!strcmp(*ptr,"|")){ //argv[] contains the input partitioned by spaces
                        //ignore the ptr for this case
char arr[2];
pipe(arr); // 0 is read 1 is write
dup2(stdout,arr[1]); // my redirected output

int a = fork();
if(a == 0){
  close(arr[0]);
  execvp(argv[0],argv);
}
     wait(NULL);

     dup2(0,arr[0]); // my redirected input 

int b = fork();
  if(b == 0){
    close(arr[1]);
    execvp(argv[2],argv);
  }
  wait(NULL);

  close(arr[0]);
  close(arr[1]);

return;

}

Joshua
  • 40,822
  • 8
  • 72
  • 132
  • 2
    We really should build a canonical instance for this -- someone asks a new version of this question every week at least. – Charles Duffy Mar 09 '19 at 01:25
  • 1
    `stdout` is a `FILE *`. The first argument to `dup2` should be an int. – William Pursell Mar 09 '19 at 01:25
  • @CharlesDuffy: homework + each question unique issues each time – Joshua Mar 09 '19 at 01:27
  • @CharlesDuffy I would definitely support a canonical instance for "how do I pipe two programs together in C" – that other guy Mar 09 '19 at 01:33
  • @Joshua, ...not *that* unique. I'm pretty sure we've seen 80% of the ways people can screw it up by now. Even if we can tell people to fix the mistakes covered in the canonical instance and come back only with new/different bugs, that's a big improvement from the status quo. – Charles Duffy Mar 09 '19 at 03:07
  • @Joshua, ...moreover, if someone hasn't split out a single, specific and unique bug and isolated their code to the shortest thing that reproduces it, they're outside both [mcve] and breadth rules. – Charles Duffy Mar 09 '19 at 03:10

1 Answers1

0

So you have 6obvious mistakes.

  1. Indent your code.
  2. Only call dup2 in the child processes.
  3. 1 not stdout, 0 not stdin.
  4. If execvp fails, call _exit.
  5. wait(NULL) is before the second fork not after
  6. arguments to dup2 are swapped

Because this is homework I'm not going to just give you the answer. Get this into shape and ping me and I'll see what more I can find.

Joshua
  • 40,822
  • 8
  • 72
  • 132