How is `dup2` actually working?

365 views Asked by At

I try to figure out how dup2 works. My goal is simply to duplicate the standard input and display it on the standard output (like a parrot :) )

I made a very basic test with a file:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main (void){
  FILE* fp= fopen("test.txt", "w");
  int fildes = fileno(fp);

  dup2(fildes, 1);
  printf("Test\n");

  close(fildes);
  fclose(fp);
  return EXIT_SUCCESS;
}

EDIT The text doesn't appear in the shell, but my file stays empty.

This is working, I made a mistake.

My idea to realize the entry duplication is something like this:

#include <stdio.h>
#include <unistd.h>   

typedef struct {
  int read;
  int write;
} pipe_t;

int main (void){
  pipe_t my_pipe;
  int pid;

  if (( pipe((int *)&my_pipe)== -1) || ( (pid = fork()) == -1))
    return 1;

  if(pid > 0){
    close(my_pipe.read);
    dup2(my_pipe.write, 0);
    int c;
    do{
      read(my_pipe.write, &c, 1);
      write(my_pipe.write, &c, 1);
      fflush(stdin);
    }while(c != '.');
    close(my_pipe.write);
  }

  else{
    close(my_pipe.write);
    dup2(my_pipe.read, 1);
    int c;
    do{
      read(my_pipe.read ,&c, 1);
      write(my_pipe.read, &c, 1);
      fflush(stdout);
    }while(c != '.');
    close(my_pipe.read);
  }
  return EXIT_SUCCESS;
}

The same code where I remove the dup2 and I replace read(my_pipe.write, &c, 1); by read(0, &c, 1); and write(my_pipe.read, &c, 1); by write(1, &c, 1); works. But this one just take inputs and do nothing.

1

There are 1 answers

2
Baroudi Safwen On

i noticed that you were opening the file for reading, may be you want to open it for writing to actually write to it.

fp = fopen("test.txt", "w")

also you should not use close() and fclose() to close the file. fclose() is more appropriate.