【linux】——进程间的通信之管道通信

通过创建命名管道实现任何一个进程的通信:

mkfifo_read.c

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<sys/types.h>
 4 #include<sys/stat.h>
 5 
 6 #include<fcntl.h>
 7 #include<stdlib.h>
 8 
 9 #define FIFO "text"
10 
11 int main(int argc, char *argv[])
12 {
13     int fd;
14     int mkfi;
15     int fd_read;
16     char buf[100];
17 
18     if(mkfifo(FIFO,O_CREAT|O_EXCL) < 0)
19     {
20         printf("mkfifo error!\n");
21         exit(1);
22     }
23     if((fd = open(FIFO,O_RDONLY|O_NONBLOCK,0)) == -1)
24     {
25         printf("open fifo error!\n");
26         exit(1);
27     }
28     while(1)
29     {
30         memset(buf,0,sizeof(buf));
31         if(fd_read = read(fd,buf,100) == -1)
32             printf("this is no data!\n");
33         else
34             printf("%s\n",buf);
35         sleep(1);
36     }    
37 }

mkfifo_write.c

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 
 4 #include<sys/stat.h>
 5 #include<sys/types.h>
 6 #include<fcntl.h>
 7 
 8 #define FIFO "text"
 9 
10 int main(int argc, char *argv[])
11 {
12     int fd;
13     int nwrite;
14     if((fd = open(FIFO,O_WRONLY|O_NONBLOCK,0)) == -1)
15     {
16         printf("open FIFO error!\n");
17         exit(1);
18     }
19         
20     if((nwrite = write(fd,argv[1],100)) == -1)
21     {
22         printf("error!\n");
23     }
24     else
25         printf("write %s\n",argv[1]);
26 }

注:

一:O_NONBLOCK 如果pathname指的是一个FIFO、一个特殊文件或一个字符特殊文件,则此选项为文件的本次打开操作和后续的I/O操作设置非阻塞模式。

原文地址:https://www.cnblogs.com/ngnetboy/p/3130776.html