1.无名管道通信时,遇到的阻塞问题时的测试。 由于无名管道有默认的阻塞特性。
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <sys/wait.h> int main(int argc,char **argv) { //管道文件,亲缘进程间通信,在内存中 fifo 半双工, int fd[2];//创建文件描述符fd[0]读 fd[1]写 if(pipe(fd)<0)//无名管道的创建 { perror("pipe error:"); exit(1); } char buf[50]="who is me!"; int x;//创建进程 for(x=0;x<1;x++) { pid_t pid=fork(); if(pid==0) break; } if(x==0) { write(fd[1],buf,strlen(buf)); } if(pid==1) { fcntl(fd[0],F_SETFL,O_NONBLOCK);//非阻塞 //fcntl(fd[0],F_SETFL,0);//阻塞 while(1) {//读取亲缘进程发送的消息 memset(buf,0,sizeof(buf)); read(fd[0],buf,sizeof(buf)); printf("buf :%s\n",buf); sleep(1); } } pid_t ret;//回收子进程 while((ret=waitpid(-1,&x,WNOHANG)!=-1) { if(ret==0) continue; if(WIFEXITED(x)) { printf("回收状态 %d\n",WEXITSTATUS(x)); } if(WIFSIGNALED(x)) { pritnf("信号杀死 %d\n",WTERMSIG(x)); } } close(fd[0]);//关闭文件描述符 close(fd[1]); return 0; }