【发布时间】:2012-09-04 13:33:09
【问题描述】:
我正在写入管道,直到用户输入字符串“end”。如果用户输入字符串“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) ... report error and stop... },然后拥有一份open()和write()。您应该考虑如果 FIFO 创建失败会发生什么。您应该考虑如果open()失败会发生什么。您可能会考虑检查来自write()的返回值。除非您成功打开fd,否则不应调用close()(但关闭应该在打开的循环中;您正在泄漏文件描述符)。您确定要在循环中打开 FIFO 吗?
标签: c linux named-pipes