以下内容仅作为本人学习笔记记录,以便后续查阅,网上有很多相同示例,不喜欢者,请礼貌划走。
1.创建有名管道,并读取终端输入发送至另一端
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
int main(void)
{
char buf[256] = {0};
int pfd = mkfifo("mpipe", 0666);
if(pfd < 0)
{
printf("mkfifo failed\n");
return 0;
}
pfd = open("mpipe", O_WRONLY);
if(pfd < 0)
{
printf("open pipe failed!\n");
return 0;
}
while(1)
{
fgets(buf, 256, stdin);
if(strcmp(buf, "quit\n") == 0) break;
write(pfd, buf, 256);
}
close(pfd);
return 0;
}
2. 接收方打开管道,并等待发送方发送数据
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
int main(void)
{
char buf[256] = {0};
int pfd = open("mpipe", O_RDONLY);
if(pfd < 0)
{
printf("open pipe failed!\n");
return 0;
}
while(read(pfd, buf, 256) > 0)
{
printf("receive: %s", buf);
}
close(pfd);
return 0;
}