管道呼叫和同步
发布时间: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,因此默认情况下读取是阻止的.因此,它等待数据写入管道.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- Angularjs的理解和认识
- Shell中read的用法详解
- Scala actors:计划多线程应用程序的两种不同方法
- 关于通过webservices调用AO组件问题
- angularjs:如何更改特定ng-view或ng-include的模板?
- 如何调整Linux系统为正确时区?
- ??o?o?Bootstrap3è?¨??????????????é?μ????????????èˉ
- 【数据结构】CODE[VS] 2491 && bzoj 3039玉蟾宫 (
- angularjs – Angular指令:绑定到父作用域中的变量
- scala – Play Idea失败 – 这个版本的sbt 0.11.3没有sbt-i