c++ - 为什么父进度无法从 ETmode 中的管道读取数据
问题描述
诶
在这里,我想将数据写入子进程中的管道文件描述符。
并在父进度中读取数据表单管道。
因为我正在学习 ET 模式,所以我向管道写入 10 个字符,睡眠 2 秒,同时从管道中读取 5 个字符。
然而结果是
res 1
aaaa
我想知道我该怎么做才能使结果像
res 1
aaaa
res 1
bbbb
...
make it can read the later charactes.
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<unistd.h>
#include<sys/epoll.h>
#include<iostream>
#include<fcntl.h>
#include"wrap.h"
#define MAXLINE 10
using namespace std;
int setnonblocking(int fd){
int old_option = fcntl(fd, F_GETFL);
int new_option = old_option|O_NONBLOCK;
fcntl(fd, F_SETFL, new_option);
return old_option;
}
int main(int argc, char* argv[]){
int efd, i;
int pfd[2];
pid_t pid;
char writebuf[MAXLINE], ch = 'a', readbuf[MAXLINE];
pipe(pfd);
pid = fork();
if(pid == 0){ // child progress
Close(pfd[0]); //close read port
while(true){
for(i = 0;i<MAXLINE/2;i++){
writebuf[i] = ch;
}
writebuf[i-1] = '\n';
ch++;
for(;i<MAXLINE;i++){
writebuf[i] = ch;
}
writebuf[i-1] = '\n';
ch++;
Write(pfd[1], writebuf, sizeof(writebuf));
setnonblocking(pfd[1]);
sleep(2);
}
Close(pfd[1]);
}
else if(pid > 0){
struct epoll_event event;
struct epoll_event resevent[10];
int res, len;
Close(pfd[1]); //close read-end of pipe
efd = epoll_create(10);
event.events = EPOLLIN|EPOLLET;
// event.events = EPOLLIN;
event.data.fd = pfd[0];
epoll_ctl(efd, EPOLL_CTL_ADD, pfd[0], &event);
setunonblocking(pfd[0]);
while(1){
res = epoll_wait(efd, resevent, 10, -1);
printf("res %d\n", res);
if(resevent[0].data.fd == pfd[0]){
len = Read(pfd[0], readbuf, MAXLINE/2);
Write(STDOUT_FILENO, readbuf, len);
}
}
Close(pfd[0]);
Close(efd);
}else{
perror("fork");
exit(-1);
}
return 0;
}
解决方案
推荐阅读
- css - 为什么我的样式表被具有较低特异性的样式表忽略?
- c# - 在非托管资源上执行 P/Invoke 时,何时需要 GC.KeepAlive(this)?
- java - 为什么我能在日期到达博物馆 +7 小时?
- c# - 控制器从 application/json 有效负载中敏感地接受数据大小写
- git - “中止:没有名为选择器的模块!” 将 Mercurial 存储库推送到 Git 存储库时
- win32gui - 如何在 win32 gui 应用程序中使用另一个事件循环
- javascript - 如果输入不存在(在数据集中),则显示通用内容
- flutter - 有没有办法在颤动中更改版本代码
- php - 如何从正在变化的字符串值中获取特定数字;php
- vim - 搞砸了我的 vim 配色方案,无法恢复