c - 如何写入命名管道而不是等待读取管道

标签 c linux named-pipes

我正在写入管道,直到用户输入字符串“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/

相关文章:

c - 如何将变量值映射到指定字符串?

objective-c - 将整数转换为十六进制

python - 无法在 Linux 服务器上以编程方式写入文件

c - 如何包含 linux/getcpu.h 等 Linux 头文件?

php - 在 Linux 中写入命名管道的最佳、最安全的方法是什么?

c - 在结构中存储数据(链表)

c - 通过 URL 获取 IP 地址

linux - 期望和 Bash 脚本

linux - 如何在程序写入/读取文件时透明地压缩/解压缩文件?

wcf - 您如何配置 WCF 以支持使用 net.pipe 的主机和客户端在同一进程中的 FaultContract?