請看看這個示例代碼,它使用非常好的編程模式將stdout
重定向到管道。爲什麼這個簡單的代碼與`exit`一起工作,而不是`_exit`工作?
#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int fd[2];
pipe(fd);
pid_t pid = fork();
if (pid == 0) {
close(fd[0]);
dup2(fd[1], 1);
printf("A string");
_exit(0);
}
close(fd[1]);
char text[1000];
size_t size;
int p = 0;
while ((size = read(fd[0], text+p, 1)) == 1) {
p++;
}
close(fd[0]);
text[p] = '\0';
printf("%s", text);
return 0;
}
該代碼,因爲它是行不通的。正如@kaylum在評論中正確建議的,在子進程中調用exit
而不是_exit
會使代碼正常工作。
'close(fd [1])'no,'close(fd [0])'也許?在你的代碼 – gsamaras
@gsamaras不是'fd [0]'管道的讀取結束,我應該在父進程中使用從管道讀取? – Zagorax
你可以關閉(fd [1]);'複製完成後,它對我來說似乎更清潔一些,但我懷疑這會改變你的程序行爲。 – jdarthenay