命名管道实现进程的信息传递【mkfifo函数、open函数】


代码实现

#include<fcntl.h> // open()
#include<sys/wait.h> // wait()
#include<sys/types.h> // mkfifo()
#include<sys/stat.h> 
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在 Linux 环境中,`mkfifo()` 函数用于创建一个命名管道命名管道是一种特殊的文件,用于实现进程间通信。它与普通文件的区别在于,它的数据只能被读取一次,读取后就被删除,不能被重复读取。 `mkfifo()` 函数的原型如下: ```c #include <sys/types.h> #include <sys/stat.h> int mkfifo(const char *pathname, mode_t mode); ``` 其中,`pathname` 参数是要创建的命名管道的路径名;`mode` 参数是文件权限,它指定了文件的访问权限和所有权等信息。 `mkfifo()` 函数成功返回 0,失败返回 -1,并设置相应的错误码。创建成功后,可以使用 `open()` 函数打开该命名管道进行读写操作,使用 `unlink()` 函数删除该文件。 下面是一个简单的示例程序,演示如何使用 `mkfifo()` 函数创建一个命名管道: ```c #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> int main(int argc, char *argv[]) { const char *fifo_file = "myfifo"; int ret; // 创建命名管道 ret = mkfifo(fifo_file, 0666); if (ret < 0) { perror("mkfifo"); exit(1); } // 打开命名管道进行读写操作 int fd = open(fifo_file, O_RDWR); if (fd < 0) { perror("open"); exit(1); } // 写入一条消息 const char *msg = "Hello, named pipe!\n"; write(fd, msg, strlen(msg)); // 关闭文件描述符 close(fd); // 删除文件 unlink(fifo_file); return 0; } ``` 在该示例程序中,我们首先使用 `mkfifo()` 函数创建了一个名为 `myfifo` 的命名管道,然后使用 `open()` 函数打开该文件进行写操作,写入一条消息后关闭文件描述符,最后使用 `unlink()` 函数删除该文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

·Jormungand

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值