加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

管道呼叫和同步

发布时间:2020-12-15 21:42:28 所属栏目:安全 来源:网络整理
导读:我正在尝试使用此代码的一些问题: #include stdio.h#include stdlib.h#define SIZE 30#define Error_(x) { perror(x); exit(1); }int main(int argc,char *argv[]) { char message[SIZE]; int pid,status,ret,fd[2]; ret = pipe(fd); if(ret == -1) Error_(
我正在尝试使用此代码的一些问题:

#include <stdio.h>
#include <stdlib.h>

#define SIZE 30
#define Error_(x) { perror(x); exit(1); }
int main(int argc,char *argv[]) {

    char message[SIZE];
    int pid,status,ret,fd[2];

    ret = pipe(fd);
    if(ret == -1) Error_("Pipe creation");

    if((pid = fork()) == -1) Error_("Fork error");

    if(pid == 0){ //child process: reader (child wants to receive data from the parent)
        close(fd[1]); //reader closes unused ch.
        while( read(fd[0],message,SIZE) > 0 )
                printf("Message: %s",message);
        close(fd[0]);
    }
    else{//parent: writer (reads from STDIN,sends data to the child)
        close(fd[0]);
        puts("Tipe some text ('quit to exit')");
        do{
            fgets(message,SIZE,stdin);
            write(fd[1],SIZE);
        }while(strcmp(message,"quitn") != 0);
        close(fd[1]);
        wait(&status);
    }
}

代码工作正常但我无法解释原因!父进程和子进程之间没有明确的同步.如果子进程在parent之前执行,则read必须返回0并且进程结束,但由于某种原因它等待父执行.你怎么解释这个?也许我错过了什么.

(编辑)的

解决方法

由于您没有在pipe2中使用O_NONBLOCK,因此默认情况下读取是阻止的.因此,它等待数据写入管道.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读