linux进程间通信--有名管道

有名管道

只有当一个库函数失败时,errno才会被设置。当函数成功运行时,errno的值不会被修改。这意味着我们不能通过测试errno的值来判断是否有错误存在。反之,只有当被调用的函数提示有错误发生时检查errno的值才有意义。
查看错误代码errno是调试程序的一个重要方法。当linux C api函数发生异常时,一般会将errno变量(需include errno.h)赋一个整数值,不同的值表示不同的含义,可以通过查看该值推测出错的原因。在实际编程中用这一招解决了不少原本看来莫名其妙的问题。
 
有名管道比无名管道更强大,它可以让无关联的进程间进行通信。
一个shell命令可以建立一个有名管道
命令格式:
mkfifo[option] name
option选项
mkfifo建立一个name的有名管道
 
如:
mkfifo fifo1   #建立一个fifo1的有名管道  --p代表管道文件
cat <  fifo1 #通过cat命令对管道进行读数据
ls  > fifo1 #ls命令显示写入管道
 
删除rm
删除有名管道函数:unlink();

列子:

读文件

#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>

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 \n");
19 }
20 printf("preparing for reading bytes..\n");
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 \n");
35 
36 }
37 printf("read%sfrom FIFO\n",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>

9 #define FIFO_SERVER "/tmp/myfifo"
10 
11 int main(int argc , char** argv)
12 {
13 int fd;
14 char w_buf[100]={'\0'};
15 int nwrite;
16 if( fd == -1 )
17 {
18 if(errno==ENXIO)
19 printf("open error\n");
20 }
21 fd=open(FIFO_SERVER,O_WRONLY|O_NONBLOCK,0);
22 if(argc == 1)
23 printf("please send something\n");
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\n");
29 }
30 else
31 printf("write %s to the FIFO\n",w_buf);

 

posted on 2015-03-17 11:41  后进后退  阅读(284)  评论(0编辑  收藏  举报