c - How is `dup2` actually working? -
i try figure out how dup2
works. goal duplicate standard input , display on standard output (like parrot :) )
i made basic test 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 shell, file stays empty.
this working, made mistake.
my idea realize entry duplication 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 remove dup2 , replace read(my_pipe.write, &c, 1);
read(0, &c, 1);
, write(my_pipe.read, &c, 1);
write(1, &c, 1);
works. 1 take inputs , nothing.
i noticed opening file reading, may want open writing write it.
fp = fopen("test.txt", "w")
also should not use close() , fclose() close file. fclose() more appropriate.
Comments
Post a Comment