使用命名管道实现进程通信

使用带参主函数

write

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
	int i = 2;
	if (argc < 2)						//判断是否传入文件名
	{
		printf("./a.out fifoname\n");
		exit(1);
	}
	int ret = access(argv[1], F_OK);	//判断fifo文件是否存在
	if (ret == -1)						//若fifo不存在就创建fifo
	{
		int r = mkfifo(argv[1], 0664);
		if (r == -1){					//判断文件是否创建成功
			perror("mkfifo");
			exit(1);
		}
		else{
			printf("fifo creat success!\n");
		}
	}
	int fd = open(argv[1], O_WRONLY);	//以读写的方式打开文件
	while (i--){						//循环写入数据
		char *p = "hello,world!";
		write(fd, p, strlen(p) + 1);
		sleep(1);
	}
	close(fd);
	return 0;
}

read

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
	
	int i =2;
	char buf[1024] = { 0 };
	if (argc < 2)							//判断是否传入文件名
	{
		printf("./a.out fifoname\n");
		exit(1);
	}
	int ret = access(argv[1], F_OK);		//判断文件是否存在
	if (ret == -1)							//若文件不存在则创建文件
	{
		int r = mkfifo(argv[1], 0664);
		if (r == -1){
			perror("mkfifo");
			exit(1);
		}
		else{
			printf("fifo creat success!\n");
		}
	}
	int fd = open(argv[1], O_RDONLY);	//打开文件
	if (fd == -1){
		perror("open");
		exit(1);
	}
	while (i--){							//不断读取fifo中的数据并打印
		char buf[1024] = { 0 };
		read(fd, buf, sizeof(buf));
		write(fd,buf,sizeof(buf));
		printf("buf=%s\n", buf);
		sleep(2);
	}
	close(fd);							//关闭文件
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值