我正在写入管道,直到用户输入字符串“end”。如果用户输入字符串“end”,我想更进一步。在这里我必须关闭管道并打印消息“After Written to Pipe”。但即使我输入了“结束”字符串,它也没有打印“写入管道后”这一行。即使没有读取管道的进程,我如何关闭管道并走得更远?..
你好,这是我的代码。,
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");
}
最佳答案
来自mkfifo(3)
手册页:
However, it has to be open at both ends simultaneously before you can proceed to do any input or output operations on it. Opening a FIFO for reading normally blocks until some other process opens the same FIFO for writing, and vice versa.
上面这段话的意思是write
会阻塞,直到有人从FIFO中读取,这就是你在你的程序中看到的。
关于c - 如何写入命名管道而不是等待读取管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12264622/