我正在寫入管道,直到用戶輸入字符串「end」。如果用戶輸入字符串「結束」,我想走得更遠。在這裏,我必須關閉管道並打印「寫入管道後」消息。但它沒有打印「寫入管道後」行,即使我輸入了「結束」字符串。 ?我怎樣才能關閉管,並進一步去偶雖然沒有進程讀取管道..如何寫入命名管道,不要等待讀取管道
你好,這裏是我的代碼,
int main() {
int fd;
char *b, *c;
printf("Enter Str : ");
b = malloc(50);
gets(b);
while(strcmp(b,"end")!=0){
if(access("MSG",F_OK) != -1) // check pipe is already available.
{
fd = open("MSG", O_WRONLY);
write(fd, b, strlen(b));
}
else
{
if(mkfifo("MSG", 0666) != -1) // create pipe if not available.
{
fd = open("MSG", O_WRONLY);
write(fd, b, strlen(b));
}
}
printf("Enter Str : ");
gets(b);
}
close(fd);
printf("After Written to Pipe");
}
那裏有一大塊(不必要的)代碼重複。你可以使用if(access(「MSG」,F_OK)!= 0){if(mkfifo(「MSG」,0666)!= 0)...報告錯誤並停止...}然後有一個副本'open()'和'write()'。您應該考慮如果FIFO創建失敗會發生什麼情況。你應該考慮如果open()失敗會發生什麼。你可能考慮檢查'write()'的返回值。除非成功地打開'fd',否則不應該調用'close()'(但是close應該在open循環中;你正在泄漏文件描述符)。你確定要打開循環中的FIFO嗎? –