- 论坛徽章:
- 0
|
首先明确一点,进程在运行过程中是互相隔离的,他们互不打扰,并且每个进程都以为自己在独占整个内存空间,既在X86平台下,每个进程都以为自己占有整个4G的内存,这当然是内存映射机制的功劳,不是今天的主题。
明确了这一点,进程在运行时有时需要跟其他的进程同步或者共享等,如一个计算,进程A需要进程B的一个数值,这就需要互相通信,linux提供了很好的通信机制,这里主要是管道通信。
1、int pipe(fd[2])
fd[2]是存放管道的两个文件描述符的数组,它只能应用与有血缘关系的两个进程,通信原理是:父进程用这个函数创建一个管道,建好后,此时已经给参数fd数组赋值了,所赋的值就是管道两端的两个文件描述符,一个读管道,一个写管道,但是这样实现的仅是一个进程读写,但是,创建的子进程,因为拷贝了父进程的地址空间和资源,因此,子进程拥有跟父进程同意的管道,因此,适当的关闭两个文件描述符,就可以轻松实现进程的通信了。
2、由于以上管道进局限于家属之间通信,因此,聪明的程序员又构造了FIFO管道机制,顾名思义,这个管道严格遵循先进先出的规则,
int mkfifo(const char *filename,mode_t mode)
FIFO管道相当于一个文件,通过这个函数可以在指定的目录上建立一个文件,因此,任意进程可以读这个管道,其他进程就可以写这个管道,非常方便的实现了进程的通信,当然,在读写管道之前,必须要像文件一样,用open打开管道,操作跟文件操作一样。
下面是一个FIFO管道实例,main函数里的参数有用户输入要写入的内容,这两个函数用的都是非阻塞读写管道。比较有意思,像QQ。
/*fifo_write.c*/
#include
#include
#include
#include
#include
#include
#include
#define FIFO "/tmp/myfifo"
main(int argc,char ** argv)
{
int fd;
char w_buf[100];
int nwrite;
if((fd=open(FIFO,O_WRONLY|O_NONBLOCK,0))==-1)
{
if(errno==ENXIO)
printf("open error;no reading process\n");
}
if(argc==1)
printf("please send something\n");
strcpy(w_buf,argv[1]);
if((nwrite=write(fd,w_buf,100))==-1)
{
if(errno==EAGAIN)
printf("The FIFO has not been read yet.Please try later\n");
else
printf("write %s to the FIFO\n",w_buf);
}
}
/*fifo_read.c*/
#include
#include
#include
#include
#include
#include
#include
#define FIFO "/tmp/myfifo"
int main(int arg,char **argv)
{
char buf_r[100];
int fd;
int nread;
if((mkfifo(FIFO,O_CREAT|O_EXCL)<0)&&(errno!=EEXIST))
printf("cannot create fifoserver\n");
printf("Preparing for reading bytes...\n");
memset(buf_r,0,sizeof(buf_r));
if((fd=open(FIFO,O_RDONLY|O_NONBLOCK,0))==-1)
{
perror("open");
exit(1);
}
while(1)
{
memset(buf_r,0,sizeof(buf_r));
if((nread=read(fd,buf_r,100))==-1)
{
if(errno==EAGAIN)
printf("no data yet \n");
}
if(*buf_r!=0){
printf("read %s from FIFO\n",buf_r);
sleep(1);}
}
pause();
unlink(FIFO);
}
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/50802/showart_404442.html |
|