我正在編寫一個程序,它需要同時雙向與外部程序進行通信,即同時讀取和寫入外部程序。分叉後退出()或_exit()?
我創建了兩個管道,一個用於將數據發送到外部進程,另一個用於從外部進程接收數據。在分解成外部程序的子進程之後,父進程再次分叉。新的孩子現在將數據寫入到外部程序的輸出管道中,父母現在從外部程序的輸入管道中讀取數據以供進一步處理。我聽說使用exit(3)可能會導致緩衝區被刷新兩次,但是我也擔心使用_exit(2)可能會留下緩衝區,使其不能被刷新。在我的程序中,分叉之前和之後都有輸出。我應該在這種情況下使用哪個(exit)(3)或_exit(2)?
以下是我的主要功能。爲簡單起見,#includes和輔助功能被省略。
int main() {
srand(time(NULL));
ssize_t n;
cin >> n;
for (double p = 0.0; p <= 1.0; p += 0.1) {
string s = generate(n, p);
int out_fd[2];
int in_fd[2];
pipe(out_fd);
pipe(in_fd);
pid_t child = fork();
if (child) {
// parent
close(out_fd[0]);
close(in_fd[1]);
if (fork()) {
close(out_fd[1]);
ssize_t size = 0;
const ssize_t block_size = 1048576;
char buf[block_size];
ssize_t n_read;
while ((n_read = read(in_fd[0], buf, block_size)) != 0) {
size += n_read;
}
size += n_read;
close(in_fd[0]);
cout << "p = " << p << "; compress ratio = " << double(size)/double(n) << '\n'; // data written before forking (the loop continues to fork)
} else {
write(out_fd[1], s.data(), s.size()); // data written after forking
exit(EXIT_SUCCESS); // exit(3) or _exit(2) ?
}
} else {
// child
close(in_fd[0]);
close(out_fd[1]);
dup2(out_fd[0], STDIN_FILENO);
dup2(in_fd[1], STDOUT_FILENO);
close(STDERR_FILENO);
execlp("xz", "xz", "-9", "--format=raw", reinterpret_cast<char *>(NULL));
}
}
}
可能重複[如何退出子進程 - \ _exit()與退出](http://stackoverflow.com/questions/2329640/how-to-exit-a-child-process-exit -vs-exit) – hvd 2013-05-04 07:51:27
@ hvd:不,我不這麼認爲。鏈接的副本是關於處理錯誤的。這種情況似乎不是關於錯誤(雖然在子進程中的錯誤處理似乎有點缺乏...... – 2013-05-04 07:55:47
@MatsPetersson我不明白這個問題是如何處理錯誤的,你能詳細說明一下嗎?速度,我認爲在那裏接受的答案中提出的觀點適用於這裏 – hvd 2013-05-04 07:59:51