c - Using dup2 from file to another file -


i'm trying execute command sort < in.txt > out.txt, using dup2. code:

    int fdin = open("in.txt",o_rdwr);     int fdout = open("out.txt",o_rdwr);      dup2(fdin,fdout);     //close(fdin);     //close(fdout);     //execvp... 

how dup2 work? can't it... thank you!

the way use closes fdout again, removing connection fdout, , connects fdin. if fdin , fdout are, maybe, 4 , 5, both 4 , 5 point in.txt.

rather that, should

dup2(fdin, 0) // 0 point same fdin dup2(fdout, 1) // 1 point same fdout close(fdin); // don't need these longer - if not 0 or 1! should checked. close(fdout); execvp(...); 

there other pitfalls taken care for, however. example, should fork() before 1 if want process go on does.

why comment @ close() above? well, when process hasn't fd 0 and/or 1 open (what unusual, not impossible), fdin might 0 or 1 , fdout might 1. these situations have cope with.

an better way be

if (fdin > 0) {     dup2(fdin, 0); // 0 point same fdin     close(fdin); } if (fdout > 1) { // cannot 0!     dup2(fdout, 1) // 1 point same fdout     close(fdout); } execvp(...); 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -