1. 说明
进程间通信方式之一是采用管道的方式就行数据传输,管道分为两种,一种是匿名管道,一种是命名管道,匿名管道仅限于本地父子进程之间的通信,而命名管道可以在不同进程之间进行通信,本篇文章将简单记录命名管道通信的实现方式。
函数说明:
mkfifo() : 创建命名管道
open() : 打开指定管道
write() : 写数据
read() : 读数据
2. 具体实现
2.1 写管道代码
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>int main()
{int fd;char message[] = "Hello from writePipe Hello from writePipe";int totalLen = strlen(message); //数据总长int perWriteLen = totalLen / 10; //分批写入管道(每批写入长度)if(access("./mypipetest", F_OK) < 0){if(mkfifo("./mypipetest", 0666) < 0) //创建命名管道{perror("mkfifo()");return -1;}}fd = open("./mypipetest", O_WRONLY); //打开管道if(fd < 0){perror("open()");return -1;}//分批循环写入管道信息for(int i = 0; i < totalLen; i += perWriteLen){int remainingChars = totalLen - i;int actualPerWriteLen = remainingChars < perWriteLen ? remainingChars : perWriteLen;int bytesWritten = write(fd, &message[i], actualPerWriteLen);printf("bytesWritten = %d\n", bytesWritten);if(bytesWritten < 0){perror("write()");return -1;}}printf("totalBytes = %d\n", totalLen);//关闭close(fd);return 0;
}
2.2 读管道代码
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>int main()
{int fd;char buffer[256];int totalLen = 41;int perReadLen = totalLen / 10;fd = open("./mypipetest", O_RDONLY); //读进程直接打开管道读取数据if(fd < 0){perror("open()");return -1;}//循环分批读取数据for(int i = 0; i < totalLen; i += perReadLen){int remainingChars = totalLen - i;int actualPerReadLen = remainingChars < perReadLen ? remainingChars : perReadLen;//读取数据时,将每次读取的数据追加到buffer缓冲中,直到读取玩所有的数据int bytesRead = read(fd, &buffer[i], actualPerReadLen);if(bytesRead < 0){perror("read()");return -1;}}buffer[totalLen] = '\0';printf("message = %s\n", buffer);//读取结束后,清空管道中的数据ftruncate(fd, 0);lseek(fd, 0, SEEK_SET);//关闭close(fd);return 0;
}
编译代码后,先运行写管道程序,再运行读管道程序,即可达到效果