我用linux管道編寫代碼,並不明白,爲什麼只有printfs(1)或只有exec(2)去到父進程的輸入。如果我評論exec,比printf工作得好。如果顯示爲什麼linux管道和exec的exec stdout不能一起工作?
int main(void)
{
int fd[2], pid;
if (pipe(fd) != 0) return 1;
if ((pid = fork()) == -1) return 1;
if (pid == 0) // child
{
close(STDOUT_FILENO);
dup2(fd[1], STDOUT_FILENO);
close(fd[0]);
close(fd[1]); // */
printf("hello\n"); // (1)
printf("hello2\n");
// execl("/bin/ls", "ls", NULL); // (2)
printf("exec not executed\n");
}
else
{
close(STDIN_FILENO);
dup2(fd[0], STDIN_FILENO);
close(fd[0]);
close(fd[1]);
char buf[100];
while(gets(buf) != NULL)
printf("message: %s\n", buf);
}
}
輸出取消註釋,只有 「LS」 輸出時EXEC評論:
消息:你好
消息:hello2
消息:EXEC不執行
時exec沒有評論:
消息:FILT1
消息:filt1.d
....其他文件
消息:生成文件
消息:objects.mk
請爲每種情況顯示程序的確切輸出。目前還不清楚「只有exec(2)進入父進程」的意思。 – kaylum