linux——FIFO命名管道(创建管道,生成特殊文件)

FIFO,也称为命名管道,它是一种文件类型。

特点:

        1、FIFO可以在无关进程之间交换数据,与无名管道不同。

        2、FIFO有路径名与之相关联,它以一种特殊设备文件形式存在于文件系统中。

api原型:(man 3 mkfifo查看)

#include <sys/types.h>
#include <sys/stat.h>

int mkfifo(const char *pathname, mode_t mode);

mode参数与open函数中mode相同。一旦创建一个FIFO,就可以用一般的文件I/O(open、read、write)函数操作它。

1、代码演示,生成file文件:

#include <sys/types.h>
#include <sys/stat.h>

//	int mkfifo(const char *pathname, mode_t mode);

int main()
{
	mkfifo("./file",0600);

	return 0;
}

编译运行,ls -l 可以看到生成一个file文件

total 20
-rwxr-xr-x 1 CLC book 8379 Apr 10 22:22 a.out
-rw-r--r-- 1 CLC book  573 Apr 10 21:53 demo1.c
-rw-r--r-- 1 CLC book  148 Apr 10 22:22 demo2.c
prw------- 1 CLC book    0 Apr 10 22:22 file

2、添加调试信息:

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>

//	int mkfifo(const char *pathname, mode_t mode);

int main()
{
	int ret=mkfifo("./file",0600);
	if(ret==0){
		printf("mkfifo success\n");
	}
	if(ret==-1){
		printf("mkfifo fail\n");
		perror("why");
	}

	return 0;
}

 修改:

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>

//	int mkfifo(const char *pathname, mode_t mode);

int main()
{
	if(mkfifo("./file",0600)==-1&&errno==EEXIST){
		printf("mkfifo fail\n");
		perror("why");
	}
	else{
		if(errno==EEXIST){
			printf("have file\n");
		}
		else
			printf("mkfifo success");
	}

	return 0;
}

当文件夹中没有file文件时,创建file并提示创建成功;否则提示创建失败,并打印原因

3、最终修改为不管文件夹有没有file文件,都不报错,也不报成功

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>

//	int mkfifo(const char *pathname, mode_t mode);

int main()
{
	if((mkfifo("./file",0600)==-1)&&errno!=EEXIST){
		printf("mkfifo fail\n");
		perror("why");
	}

	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值