命名管道

命名管道

与匿名管道相比,命名管道使两个没有血缘关系的进程看到同一份临界资源。

管道创建:

可以用mkfifo也可以用mknod

#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char* filename, mode_t mode)
int mknod(const char* filename, mode_t mode | S_SIFIF0, (dev_t)0)
;

这两个函数都很会创建一个FIFO文件,这个文件见真实存在于系统文件中,filename指定了该文件的名称,mode指定文件的读写权限。 
管道文件创建好后,使两个进程实现通信,注意该通信是单向的。即一个读端一个写端。

测试代码:

fifo_write.c

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>

#define PATH "/tmp/file.tmp"
#define SIZE 1024

int main(int argc, char const *argv[])
{
//创建一个命名管道文件,并设置权限对任何人可读可写可执行
int ret = mkfifo(PATH, 0666 | S_IFIFO);
if (-1 == ret){
perror("mkfifo");
return 1;
}
//打开该文件
int fd = open(PATH, O_WRONLY);
if (fd < 0){
perror("open");
return 2;
}
//buf是写入缓冲区
char buf[SIZE];
memset(buf, 0, sizeof(buf));
while (1){
scanf("%s",buf);
int ret = write(fd, buf, strlen(buf) + 1);
if (ret < 0){
perror("write");
return 3;
}
if (strncmp(buf, "quit", 4) == 0){
break;
}
}

close(fd);
return 0;
}

fifo_read.c

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

#define SIZE 1024
#define PATH "/tmp/file.tmp"

int main(int argc, char const *argv[])
{
int fd = open(PATH, O_RDONLY);
if (fd < 0){
perror("open");
return fd;
}
//buf是读取数据的缓冲区
char buf[SIZE];
memset(buf, 0, sizeof(buf));
while (1){
int ret = read(fd, buf, sizeof(buf));
if (ret <= 0){
perror("read");
break;
}
printf("%s\n", buf);
if (strncmp(buf, "quit", 4) == 0){//???
break;
}
}
close(fd);
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值