int p[2];
if (pipe(p) != 0) ...report error and do not continue...
pid_t pid = fork();
if (pid < 0) ...report error, close pipe descriptors, and do not continue...
if (pid == 0)
{
/* Child - becomes sort */
dup2(p[0], 0);
close(p[0]);
close(p[1]);
int fd = open("output-file", O_CREAT | O_EXCL | O_WRONLY, 0644);
if (fd < 0) ...report error and exit...
dup2(fd, 1);
close(fd);
execlp("sort", "sort", (char *)0);
...report error and exit...
}
else
{
/* Parent - writes data to sort */
close(fd[0]);
...write data to fd[1]...
close(fd[1]);
int status;
int corpse;
while ((corpse = wait(&status)) > 0 && corpse != pid)
...consider reporting which child died...
...consider reporting sort status...
...continue with the rest of the program...
}
你可以決定是否上報相關dup2()
失敗,或close()
失敗的錯誤。除了報告問題和退出外,在任何情況下都無能爲力。除非有人通過不提供標準輸入,標準輸出和標準錯誤(或程序中其他地方關閉了任何標準通道)而使您的程序受到殘酷和異常的懲罰,否則管道和文件描述符不能標準的I/O描述符,所以關閉是安全的。如果你不知道你的用戶是如何生病的是,你可以保護關閉:
if (p[0] > FILENO_STDERR)
close(p[0]);
這通常是不必要的偏執(但它可以與缺少標準I/O有趣的嘗試計劃)。
你已經試過了什麼? –
這可能有所幫助:http://en.wikipedia.org/wiki/Named_pipe –
@martinclayton,爲什麼在這裏需要命名管道?根據需要,可以簡單地將'mkpipe()'返回的FD附加到stdin或stdout。 –