您的位置:首页 > 游戏 > 手游 > 免费推广网手机版_陕西网络推广维护_湖南网站制作公司_公众号seo排名软件

免费推广网手机版_陕西网络推广维护_湖南网站制作公司_公众号seo排名软件

2025/3/11 1:31:44 来源:https://blog.csdn.net/FY_13781298928/article/details/144473450  浏览:    关键词:免费推广网手机版_陕西网络推广维护_湖南网站制作公司_公众号seo排名软件
免费推广网手机版_陕西网络推广维护_湖南网站制作公司_公众号seo排名软件

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;
}

编译代码后,先运行写管道程序,再运行读管道程序,即可达到效果

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com