进程通信-有名管道FIFO

FIFO:有名管道
原型:int mkfifo(const char *pathname,mode_t mode);头文件:sys/types.h和sys/stat.h
参数:创建的管道名字和操作权限
说明:可以在任意两个进程中通信
返回值:成功则返回0,否则返回-1,错误原因存于errno中
说明:1.管道有大小限制(4096B) 在写入数据之前,会先判断管道大小是否足够,若不够就不会写入 
            写满后只能等到有数据被读出才能继续写入.
         2.read读数据是一定要读到数据才能返回的,否则就会等待,全部进程中必须有一个reader
            是没有关闭的,才能write进数据.
         3.writer设置成非阻塞,必须先运行readr,否则写端会受到警告No such device or address 
         4.open(fifo, O_RDONLY);open(fifo, O_WRONLY);这种是阻塞模式,不管先运行哪一个都会
            等另一个进程open的时候才能open结束(,两个进程间?非父子进程)

         5.open(fifo,O_RDONLY|O_NONBLOCK);open(fifo,O_WRONLY|O_NONBLOCK);非阻塞模式,

           前者不用等写打开就可以open结束,但是先运行后者就不可以:说明3

父子进程间测试:

#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
int main(void)
{
char buf[80];
int fd;
unlink("myfifo");//先清理掉无用的,否则会报错已经存在
mkfifo("myfifo",0777 );
if ( fork() > 0 )
{
char s[] = "Hello!\n";
fd = open("myfifo", O_WRONLY );
write( fd, s, sizeof(s) );
close( fd );
}
else
{
fd = open( "myfifo", O_RDONLY );
read( fd, buf, sizeof(buf) );
printf("The message from the pipe is:%s\n", buf );
close( fd );
}
return 0;
}
测试结果:

[root@libmaster zxd]# ./a.out 
The message from the pipe is:Hello!

两个进程之间测试:

读端:

#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>

#define FIFO "/home/zxd/zxd/ififo"

int main(void)
{
	int fd;
	char buf[128];
        unlink(FIFO);//清理不再使用的文件
	if(mkfifo(FIFO, 0666))//创建管道文件
	{
		 perror("Mkfifo error");
	}
	printf("open for reading... \n");
      //fd=open(FIFO,O_RDONLY);//阻塞
	fd=open(FIFO,O_RDONLY|O_NONBLOCK);//非阻塞
	printf("FIFO reader opened \n");
	if(fd<0)
	{
		perror("Failed to open fifo:");
		return -1;
	}

	while(1)
	{
		int count;
		count=read(fd,buf,127);
		if(count>0)
		{
			buf[count]=0;//结束符,也可以='\0';
			printf("fifoReader receive a string:%s\n",buf);
		}
		if(strncmp(buf,"exit",4)==0)
		{
			break;
		}
	}
	close(fd);	
	return 0;
}
写端:

#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <signal.h>

#define FIFO "/home/zxd/zxd/ififo"

int main(void)
{
	int fd;
	char buf[128];
        printf("open for writing ... \n");
      //fd=open(FIFO,O_WRONLY);// 阻塞
	fd=open(FIFO,O_WRONLY|O_NONBLOCK);//非阻塞,不能先于读端运行,否则 open失败
	printf("FIFO writer opened \n");
	if(fd<0)
	{
		perror("Failed to open fifo:");
		return -1;
	}
	
	while(1)
	{
		fgets(buf,128,stdin);//标准输入内容
		write(fd,buf,strlen(buf));//把缓存写入
		if(strncmp(buf,"exit",4)==0)
		{
			break;
		}
	}
	close(fd);
	unlink(FIFO);	
	return 0;
}
结果:

[root@libmaster zxd]# ./read 
open for reading... 
FIFO reader opened 
fifoReader receive a string:hello
fifoReader receive a string:exit


[root@libmaster zxd]# ./write 
open for writing ... 
FIFO writer opened 
hello
exit


猜你喜欢

转载自blog.csdn.net/linuxzhuxiaodi/article/details/78506826