C语言有名管道fifo的创建及运用

时间:2021-11-19 15:12:13
三个文件(fifo.c,write.c,read.c)
fifo.c用来创建有名管道fifo(最先编译)
write.c用来向管道写入数据

read.c用来从管道读出数据

==================================================
//文件1:fifo.c

#include <stdio.h>
#include <string.h>
#include <error.h>
#include <fcntl.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
int result;
if(argc!=2)//判断是否有两个参数
{
printf("input error\n");
exit(1);
}
else
{
result=access(argv[1],F_OK);//判断该文件是否存在
if(result==0)//存在
{
unlink(argv[1]);//删除同名文件
}
}
int ret;
ret=mkfifo(argv[1],0644);//创建有名管道
if(ret!=0)
{
perror("mkfifo error");
exit(1);
}
}

==================================================
//文件2:write.c

#include <stdio.h>
#include <fcntl.h>
#include <error.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 128
int main()
{
char buffer[SIZE];
int write_fd;
int ret;
int len;
do
{
write_fd=open("./swap",O_WRONLY);//打开管道(只写)
if(write_fd<0)
{
perror("open error");
exit(1);
}
printf("input data\n");
fgets(buffer,SIZE,stdin);
len=strlen(buffer);
buffer[len-1]='\0';
ret=write(write_fd,buffer,SIZE);
if(ret==-1)
{
perror("write error");
exit(1);
}
printf("send success\n");
close(write_fd);
}while(strcmp(buffer,"exit")!=0);
return 0;
}

==================================================
//文件3:read.c

#include <stdio.h>
#include <fcntl.h>
#include <error.h>
#include <stdlib.h>
#define SIZE 128
int main()
{
char buffer[SIZE];
int read_fd;
int ret;
do
{
read_fd=open("./swap",O_RDONLY);
if(read_fd<0)
{
perror("open error");
exit(1);
}
ret=read(read_fd,buffer,SIZE);
if(ret==-1)
{
perror("read error");
exit(1);
}
printf("the data is:\n");
printf("%s\n",buffer);
close(read_fd);
}while(strcmp(buffer,"exit")!=0);
return 0;
}
编译命令


gcc fifo.c -o f
./f swap
gcc read.c -o r
gcc write.c -o w