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

作业社区

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

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

枝wenz_fpJNR0 的学生作业:

#include #include #include #include #include #define BUF_SIZE 1024 int main(int argc, char const *argv[]) { 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){ // 子进程 // 从管道读取数据 size_t rbytes; char buf[BUF_SIZE]; close(pipefd[1]);//关闭写端 // 从管道读取数据,直到读取到空数据 while((rbytes = read(pipefd[0], buf, BUF_SIZE)) > 0){ buf[rbytes] = '\0';//添加结束符 printf("子进程读取到的数据: %s\n",buf);//打印读取到的数据 } if (rbytes == -1) { perror("[ERROR] read() :"); close(pipefd[0]);//关闭读端 exit(EXIT_FAILURE); wait(NULL);//等待子进程结束 } // printf("子进程读取到的数据: %s", buf); close(pipefd[0]);//关闭读端 wait(NULL);//等待子进程结束 }else if (cpid > 0) { // 父进程 // 向管道写入数据 close(pipefd[0]);//关闭读端 size_t wbytes;//写入的字节数 char input[BUF_SIZE];//要写入的数据 while(1){ printf("请输入要写入的数据: ");//提示用户输入 if(fgets(input, BUF_SIZE, stdin) == NULL){//读取用户输入 break; } input[strlen(input)-1] = '\0';//移除换行符 if(strcmp(input, "quit") == 0){//如果用户输入quit,则退出循环 break; } wbytes = write(pipefd[1], input, strlen(input));//向管道写入数据 } if (wbytes == -1) { perror("[ERROR] write() :"); close(pipefd[1]);//关闭写端 exit(EXIT_FAILURE); wait(NULL);//等待子进程结束 } printf("父进程写入数据: %s", input); printf("\n"); close(pipefd[1]);//关闭写端 wait(NULL);//等待子进程结束 } return 0; }

微信客服

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

帮助反馈 APP下载

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

公众号

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