有名管道
列子:
读文件
#include<sys/types.h>
2 #include<sys/stat.h>
3 #include<errno.h>
4 #include<fcntl.h>
5 #include<stdio.h>
6 #include<string.h>
7 #include<stdlib.h>
8
9 #define FIFO "/tmp/myfifo"
10
11 int main(int argc , char**argv)
12 {
13 char buf_r[100];
14 int fd;
15 int nread;
16 if(( mkfifo(FIFO,O_CREAT|O_EXCL) < 0)&&(errno != EEXIST))
17 {
18 printf("can't create fifoserver
");
19 }
20 printf("preparing for reading bytes..
");
21 memset(buf_r, 0,sizeof(buf_r));
22 fd=open(FIFO,O_RDONLY|O_NONBLOCK,0);
23 if(fd == -1)
24 {
25 perror("open");
26 exit(1);
27 }
28 while(1)
29 {
30 memset(buf_r, 0,sizeof(buf_r));
31 if(nread=read(fd,buf_r ,100)== -1)
32 {
33 if(errno==EAGAIN)
34 printf("no data
");
35
36 }
37 printf("read%sfrom FIFO
",buf_r);
38 sleep(1);
39 }
40 pause();
41 unlink(FIFO);
42 }
写文件
1 #include<sys/types.h>
2 #include<sys/stat.h>
3 #include<errno.h>
4 #include<fcntl.h>
5 #include<stdio.h>
6 #include<stdlib.h>
7 #include<string.h>
8
9 #define FIFO_SERVER "/tmp/myfifo"
10
11 int main(int argc , char** argv)
12 {
13 int fd;
14 char w_buf[100]={' '};
15 int nwrite;
16 if( fd == -1 )
17 {
18 if(errno==ENXIO)
19 printf("open error
");
20 }
21 fd=open(FIFO_SERVER,O_WRONLY|O_NONBLOCK,0);
22 if(argc == 1)
23 printf("please send something
");
24 strcpy(w_buf,argv[1]);
25 if( (nwrite = write(fd,w_buf,100) )== -1 )
26 {
27 if( errno == EAGAIN)
28 printf("The FIFO has not been read yet
");
29 }
30 else
31 printf("write %s to the FIFO
",w_buf);