代码拉取完成,页面将自动刷新
#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;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。