标签:int 写入 C语言 间通信 管道 fd include buf
写端程序:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main()
{
// 往管道里面写数据
// 创建之前首先判断管道文件是否存在
// 使用F_OK宏判断文件访问是否OK
int ret = access("test", F_OK);
if (ret == -1)
{
printf("管道不存在,创建\n");
ret = mkfifo("test", 0664);
if (ret == -1)
{
perror("mkfifo");
exit(0);
}
}
// 打开管道,以只写的方式读取管道
int fd = open("test", O_WRONLY);
if (fd == -1)
{
perror("open");
exit(0);
}
// 写数据
for (int i = 0; i, 100; i++)
{
char buf[1024];
sprintf(buf, "hello, %d\n", i);
printf("写入的数据是%s: ", buf);
write(fd, buf, strlen(buf));
sleep(1);
}
close(fd);
return 0;
}
读端程序:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main()
{
// 从管道读取数据
// 打开管道,以只读的方式读取管道
int fd = open("test", O_RDONLY);
if (fd == -1)
{
perror("open");
exit(0);
}
// 读数据
while (1)
{
char buf[1024] = {0};
int len = read(fd, buf, sizeof(buf));
if (len == 0)
{
printf("写端断开连接。。。。。。。。\n");
break;
}
printf("收到的数据是:%s", buf);
}
close(fd);
return 0;
}
这两个程序,前者向管道中写入数据,后者从管道中读取数据
如果先运行前者,而后者未运行
那么前者会一直阻塞,且不会向管道中写入任何数据,直到后者开始运行
如果先运行后者,而前者未运行
那么显然也会阻塞,因为管道中不存在任何数据,直到前者运行(向管道中写入数据)
前者运行之后,然后后者运行,此时前者开始向管道中写入数据,后者从管道中读取数据,如果此时突然终止后者,那么前者也会随之终止(不是写入终止,而是整个程序会直接终止,因为写端被打开后,又关闭了,注意和一开始就没有被打开这种情况进行区分)
标签:int,写入,C语言,间通信,管道,fd,include,buf 来源: https://blog.csdn.net/ma_de_hao_mei_le/article/details/123076333
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。