进程间通讯-无名管道 课后练习
我要参与
进程间通讯-无名管道 课后练习
学习任务 2.2k
等106人参与

练习

创建一个子进程,负责循环从管道中读取数据,父进程从键盘读取数据后,写入到管道中,输入 “quit” 字符串时退出

去发布

登录后即可发布作业,立即

我的作业

全部作业 4

蜡笔小方哎
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>

int main()
{
        int pipefd[2];
        pid_t pid;
        if(pipe(pipefd) == -1)
        {
                perror("pipe() error!\n");
        }

        pid = fork();
        if(pid == -1)
        {
                perror("fork error()!\n");
                close(pipefd[0]);
                close(pipefd[1]);
                exit(-1);
        }
        else if(pid == 0)
        {
                close(pipefd[1]);

                char buffer[100];
                while(1)
                {
                        memset(buffer, 0, sizeof(buffer));
                        read(pipefd[0], buffer, sizeof(buffer));

                        if(strcmp(buffer, "quit") == 0)
                                break;

                        printf("child process: %s\n", buffer);
                }

                close(pipefd[0]);
        }
        else
        {
                close(pipefd[0]);

                char str[100];
                while(1)
                {
                        memset(str, 0, sizeof(str));
                        printf("input> ");
                        fgets(str, sizeof(str), stdin);
                        str[strlen(str)-1] = '\0';
#ifdef DEBUG
                        printf("[DEBUG] fgets: %s\n", str);
#endif
                        write(pipefd[1], str, strlen(str));
                        if(strcmp(str, "quit") == 0)
                        {
                                wait(NULL);
                                break;
                        }

                }

                close(pipefd[1]);
        }

        return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
代码块
复制 预览
复制成功!
提交于  2025-03-19 13:50:00
评论 1
讲师点评
评分:100
无__名
微信客服

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

帮助反馈 APP下载

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

公众号

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

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师