管道在读写过程容易造成阻塞,可以强行在读取时设置为非阻塞:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<fcntl.h>
#include<unistd.h>
#define SIZE 64
int main(void)
{
int fd[2];
pid_t pid=-1;
int ret=-1;
char buf[SIZE];
//创建无名管道
ret=pipe(fd);
if(-1==ret)
{
perror("pipe");
return 1;
}
pid=fork();
if(-1==pid)
{
perror("fork");
return 1;
}
//子进程
if(0==pid)
{
close(fd[1]);
memset(buf,0,SIZE);
printf("子进程读取管道的内容...\n");
//设置读端为非阻塞
ret=fcntl(fd[0],F_GETFL);
ret |=O_NONBLOCK;
fcntl(fd[0],F_SETFL,ret);
//读管道
ret=read(fd[0],buf,SIZE);
if(ret<0)
{
perror("read");
exit(-1);
}
printf("child process buf:%s\n",buf);
close(fd[0]);
exit(0);
};
//父进程
close(fd[0]);
sleep(1);
ret=write(fd[1],"abcdefghijk",10);
if(ret<0)
{
perror("write");
return 1;
}
printf("parent process write len:%d\n",ret);
close(fd[1]);
return 0;
}
read:Resource temporarily unavailable