- 论坛徽章:
- 0
|
你知道为什么按照你的代码 3(sleep2秒) 会在 1之前输出吗
因为fd=open(FIFO,O_RDONLY); 在write之前是一直不返回,被阻塞住的,所以3 会在1之前输出
所以统一的把mode改成O_RDWR
然后再把fcntl(fd, F_SETOWN, getpid( ));加进去,
修改后代码如下, 你再try下- #include<sys/types.h>
- #include<sys/stat.h>
- #include<fcntl.h>
- #include<stdio.h>
- #include<stdlib.h>
- #include<unistd.h>
- #include<signal.h>
- char buf[6]={0};
- int fd;
- void f(int signo){
- printf("step5: read content=%s\n",buf);
- }
- int main(void){
- char FIFO[]="myfifo";
- unlink(FIFO);
- mkfifo(FIFO,0666);
- pid_t p=fork();
- if(p==0){//child
- sleep(2);
- printf("step3: child begin\n");
- fd=open(FIFO,O_RDWR/*O_WRONLY*/);
- int flags=fcntl(fd,F_GETFL);
- if(flags<0){
- printf("fcntl get failed\n");
- return 1;
- }
- if(fcntl(fd,F_SETFL,flags|O_NONBLOCK|FASYNC)==-1){
- printf("fcntl set failed\n");
- return 1;
- }
- write(fd,"hello",5);
- printf("step4: write ok\n");
- close(fd);
- }else if(p>0){//father
- signal(SIGIO,f);
- fd=open(FIFO,O_RDWR/*O_RDONLY*/);
- fcntl(fd,F_SETOWN,getpid());
- int flags=fcntl(fd,F_GETFL);
- if(flags<0){
- printf("fcntl get failed\n");
- return 1;
- }
- if(fcntl(fd,F_SETFL,flags|O_NONBLOCK|FASYNC)==-1){
- printf("fcntl set failed\n");
- return 1;
- }
- printf("step1: begin async read\n");
- read(fd,buf,sizeof(buf));
- printf("step2: read done\n");
- sleep(4);
- printf("step6: father wake up\n");
- close(fd);
- }else{}//error
- return 0;
- }
复制代码 |
|