为了账号安全,请及时绑定邮箱和手机立即绑定

作业社区

探索学习新天地,共享知识资源!

0 提交作业
0 布置作业
0 满分作业
得分 100
学习任务

jelasin 的学生作业:

#define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include int main(int argc,char *argv[]) { fd_set read_fds; int pipefd[2]; if(pipe(pipefd) < 0) { perror("pipe"); return 1; } FD_ZERO(&read_fds); FD_SET(pipefd[0], &read_fds); pid_t pid = fork(); if(pid < 0) { perror("fork"); return 1; } else if(pid == 0) { close(pipefd[0]); while (true) { printf("child: waiting for input\n"); char buf[100]; read(0, buf, 100); write(pipefd[1], buf, strlen(buf)); printf("child: wrote %lu bytes: %s\n", strlen(buf), buf); if (strcmp(buf, "exit\n") == 0) { break; } } close(pipefd[1]); exit(0); } else { sleep(1); close(pipefd[1]); char buf[100]; while (true) { int ret = select(pipefd[0] + 1, &read_fds, NULL, NULL, NULL); if(ret < 0) { perror("select"); } else if(ret == 0) { printf("timeout\n"); } else { if(FD_ISSET(pipefd[0], &read_fds)) { printf("pipe is ready to read\n"); read(pipefd[0], buf, 100); printf("read %lu bytes: %s\n", strlen(buf), buf); if (strcmp(buf, "exit\n") == 0) { break; } } } } close(pipefd[0]); waitpid(pid, NULL, 0); } return 0; } ➜ 5 ./main child: waiting for input aaachild: wrote 3 bytes: aaa child: waiting for input pipe is ready to read read 3 bytes: aaa bbbbchild: wrote 4 bytes: bbbb child: waiting for input pipe is ready to read read 4 bytes: bbbb exit child: wrote 5 bytes: exit pipe is ready to read read 5 bytes: exit

微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号