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

作业社区

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

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

沫颖 的学生作业:

代码 #include #include #include #include #include #include int main(void) { pid_t cpid; // 创建管道后的文件描述符返回值 int ret; // 管道文件描述符存放位置 int pipefd[2]; // 创建管道 ret = pipe(pipefd); if (ret == -1) { perror("[ERROR] pipe() :"); exit(EXIT_FAILURE); } // 创建进程 cpid = fork(); if (cpid == -1) { perror("[ERROR] fork() :"); exit(EXIT_FAILURE); } // 子进程 else if (cpid == 0) { // 读取的字符串信息 ssize_t rbytes; char buffer[64] = {0}; close(pipefd[1]); // 关闭子进程写端文件描述符,只处理读端 while (1) { rbytes = read(pipefd[0], buffer, sizeof(buffer)); // 当管道中没有数据,会阻塞,预留处理字符串终止符 \0 if (rbytes == -1) { perror("[ERROR] read() :"); // 关闭读端文件描述符 close(pipefd[0]); exit(EXIT_FAILURE); } else if (rbytes == 0) { // 管道被关闭 break; } // 如果主进程输入的是“quit”,则主动退出 if (strcmp(buffer, "quit") == 0) { // 关闭读端文件描述符 close(pipefd[0]); exit(EXIT_SUCCESS); } else { printf("buffer : %s\n", buffer); } } } // 主进程 else if (cpid > 0) { ssize_t wbytes; char buffer[64]; close(pipefd[0]); while (1) { printf("please input charstr :\n"); scanf("%63s", buffer); // 防止缓冲区溢出 // 关闭主进程读端文件描述符,只处理写端 wbytes = write(pipefd[1], buffer, strlen(buffer) + 1); // 写入字符串终止符 if (wbytes == -1) { perror("[ERROR] write(): "); close(pipefd[1]); wait(NULL); exit(EXIT_FAILURE); } // 如果主进程输入的是“quit”,则关闭写端文件描述符 if (strcmp(buffer, "quit") == 0) { close(pipefd[1]); wait(NULL); exit(EXIT_SUCCESS); } } close(pipefd[1]); wait(NULL); exit(EXIT_SUCCESS); } return 0; } 结果 please input charstr : qweqw please input charstr : buffer : qweqw asdas please input charstr : buffer : asdas quit

微信客服

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

帮助反馈 APP下载

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

公众号

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