1 Star 0 Fork 0

uu/homework6

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
testPipe.cc 3.04 KB
一键复制 编辑 原始数据 按行查看 历史
uu 提交于 2026-01-21 09:21 +08:00 . 匿名管道的使用
#include <iostream>
#include <unistd.h>
#include <cstdio>
#include <string>
#include <cstring>
#include <cstdlib>
#include <sys/types.h>
#include <sys/wait.h>
#define N 2
#define NUM 1024
using namespace std;
//子进程
void Writer(int wfd)
{
string str = "hello, I am a child";
pid_t slef = getpid();
int number = 0;
char buffer[NUM];
while(true)
{
//3.写端每隔1秒写一次,读端读5秒关闭
sleep(1);//1.慢慢写,读端一直读,看看情况如何
//构建发送字符串
buffer[0] = 0;//字符串清空,只是为了提醒阅读代码的人,我们把这个数组当作字符串了
snprintf(buffer, sizeof(buffer), "%s-%d-%d", str.c_str(), slef, number++);
//cout << buffer << endl;
//发送\写入给父进程
write(wfd, buffer, strlen(buffer));//写入字符串内容即可,不用写入 \0(只是C语言字符串结束标志,文件可以控制字节数)
// write(wfd, "c", 1);
// cout << number << endl;//写满为65536个字节,64KB
//每隔一秒写入
// sleep(1);
//2.写端关闭,读端的情况如何?
// if(number >= 5) break;
}
}
//父进程
void Reader(int rfd)
{
char buffer[NUM];
int cnt = 0;
while(true)
{
// sleep(1);
ssize_t n = read(rfd, buffer, sizeof(buffer) - 1);//留一个位置给\0
if(n > 0)
{
buffer[n] = 0;//手动添加 \0
cout << "father[" << getpid() << "]get a message: " << buffer << endl;
}
else if(n == 0)
{
cout << "father read the end of the file!" << endl;
break;//读到了文件结尾就不用读了
}
else break;//读取出错
//3.读端读5秒后关闭,写端一直写
if(++cnt > 5) break;
cout << "cnt: " << cnt << endl;
// cout << "n: " << n << endl;
}
}
int main()
{
//创建管道
int pipeid[N] = {0};
int n = pipe(pipeid);
if(n < 0) return 1;
// cout << "pipeid[0]: " << pipeid[0] << ", pipeid[1: " << pipeid[1] << endl;
//创建子进程
//子进程写入(关闭读),父进程读取(关闭写)
pid_t id = fork();
if(id < 0) return 2;
else if(id == 0)
{
//子进程
close(pipeid[0]);
//通信代码
Writer(pipeid[1]);
close(pipeid[1]);//可以不关,后续由操作系统回收
exit(0);
}
//父进程
close(pipeid[1]);
//通信代码
Reader(pipeid[0]);//3.读端读5秒后关闭,写端一直写
close(pipeid[0]);//可以不关,后续后操作系统回收
std::cout << "father close read fd: " << pipeid[0] << endl;
sleep(5);//观察僵尸状态
//等待子进程
int status = 0;
pid_t ret = waitpid(id, &status, 0);
if(ret < 0) return 3;
cout << "wait child success: "<< ret << "exit code: " << WEXITSTATUS(status) << "exit signal: " << WTERMSIG(status) << endl;
sleep(5);//观察回收过程
cout << "father quit" << endl;
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/dongfanqi/homework6.git
git@gitee.com:dongfanqi/homework6.git
dongfanqi
homework6
homework6
master

搜索帮助