Bash   发布时间:2022-05-13  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了管道呼叫和同步大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用此代码的一些问题:

#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,"quit\n") != 0);
        close(fd[1]);
        wait(&status);
    }
}

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

(编辑)的

解决方法

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

大佬总结

以上是大佬教程为你收集整理的管道呼叫和同步全部内容,希望文章能够帮你解决管道呼叫和同步所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: