[問題] dup2()的問題

看板LinuxDev作者 (scrya)時間15年前 (2010/12/24 22:26), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串1/1
以下的程式會看某執行檔的輸出結果是否正確, 所以用了redirect的機制: #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/wait.h> #include <fstream> #include <iostream> #include <string> using namespace std; int main() { pid_t pid; int infildes, judgefildes; string command, exename, infilename, outfilename, judgefilename; fstream outfile, judgefile; while(cin >> exename >> infilename >> outfilename) { command = "./" + exename; judgefilename = "_" + outfilename; judgefile.open(judgefilename.c_str(),fstream::in|fstream::out|fstream::trunc); judgefile.close(); pid = fork(); if(pid < 0){ cerr << "fork failed\n"; return 1; } else if(pid == 0){ infildes = open(infilename.c_str(),O_RDONLY); judgefildes = open(judgefilename.c_str(),O_RDWR); /* 好奇的地方 */ close(0); dup2(infildes,0); close(infildes); close(1); dup2(judgefildes,1); close(judgefildes); execlp(command.c_str(),exename.c_str(),0); } else{ string outfile_content, judgefile_content; /* 好奇的地方 */ outfile.open(outfilename.c_str(),fstream::in); judgefile.open(judgefilename.c_str(),fstream::in); while(!outfile.eof()) outfile_content += outfile.get(); while(!judgefile.eof()) judgefile_content += judgefile.get(); if(outfile_content != judgefile_content) cout << "WRONG-ANSWER" << endl; else cout << "CORRECT!" << endl; outfile.close(); judgefile.close(); } } return 0; } 只是我覺得很有趣的地方是:在child process的部分用了重導,使stdout的結果 會存入檔案中,那麼在parent process的地方,judgefile所要開啟的檔案或是 stdout的串流會不會受到child process的影響,而導致parent process的 stdout或是在開啟judgefile的時候,發生一些串流的錯誤(找錯地方) 希望能得到解答(我覺得緩衝區的buffer會被複製,所以好像不會有影響) -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 111.251.173.115
文章代碼(AID): #1D5AsNfW (LinuxDev)
文章代碼(AID): #1D5AsNfW (LinuxDev)