Linux进程管道通信示例

Linux管道通信示例

因为进程的变量内存独立,所以进程之间的通信不能用全局变量或者指针等,只能使用文件作为相互通信方式,管道、信号、共享内存实质都是文件,操作方式都是文件操作
管道通信有两种,有名管道和匿名管道,匿名管道是内核4k空间只能用在父子进程,有名管道是硬盘上没有限制,
还要注意以下
 1、管道通信单向的,只能一个进程写,另一个进程读,要实现双向通信就必须建两个管道
 2、管道文件最大4k,如果写满了,写函数会被阻塞,写进程会卡在写函数
 3、管道为空的时候,读函数会被阻塞,读进程会卡在读函数
头文件
 #include <unistd.h>
原函数
 匿名管道创建
 int pipe (int fd[2]);
 命名管道创建
 #include <sys/stat.h>
 int mknod(const char* path, mode_t mod, dev_t dev);
 int mkfifo(const char* path, mode_t mod);

下面程序创建一个管道文件,并创建两个进程,一个进程读管道并打印管道读出的内容,一个进程写管道
程序示例

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>

#include<unistd.h>   
#include<errno.h> 


void create_mkfifo()
{
    
    
	if(mkfifo("./my_mkfifo",0777) != 0 )
    {
    
    
        if(errno == EEXIST) //当该有名管道存在时,提示下
        {
    
    
            printf("File exists\n");
        }
        else
        {
    
    
            perror("mkfifo fail ");
            exit(1);
        }
	}
}

void fifo_write(char *s,int len)
{
    
    
	int fd;
	fd = open("./my_mkfifo",O_RDWR);//读写方式打开,使用文件IO 操作有名管道
    if(fd < 0)
    {
    
    
        perror("open fifo fail: ");
        exit(1);
    }
	else
	{
    
    
		write(fd,s,len);
	}
}

int fifo_read(char *s,int len)
{
    
    
	int fd,rtn_len;
	fd = open("./my_mkfifo",O_RDWR);//读写方式打开,使用文件IO 操作有名管道
    if(fd < 0)
    {
    
    
        perror("open fifo fail: ");
        exit(1);
    }
	else
	{
    
    
		rtn_len = read(fd,s,len);
	}
	return rtn_len;
}

//进程1
void process1(void)
{
    
    
	while(1)
	{
    
    
		printf("process1:write fifo\n"); 
		fifo_write("hello guoguo\r\n mkfifo test\r\n",28);
		sleep(1);
	}
}

//进程2
void process2(void)
{
    
    
	char buf[100];
	int len;
	
	while(1)
	{
    
    
		printf("process2:read fifo\n"); 
		len = fifo_read(buf, 100);
		printf("%s",buf);
		memset(buf,0,100);
	}
}

int main(int argc, const char *argv[])
{
    
    
	pid_t pid,pid1;
	
	create_mkfifo();
	
//创建2个进程
	pid = fork(); 
	if(pid == 0)
	{
    
    
		printf("process1 create ok\n");  
		process1();
	}
	else if(pid < 0)
		{
    
    
			printf("process create failed\n"); 
			perror("fork");  
		}
		else
		{
    
    

		}
	pid1 = fork(); 
	if(pid1 == 0)
	{
    
    
		printf("process create ok\n");  
		process2();
	}
	else if(pid < 0)
		{
    
    
			printf("process create failed\n"); 
			perror("fork");  
		}
		else
		{
    
    
			
		}
 
    return 0;
}

おすすめ

転載: blog.csdn.net/u010835747/article/details/105160382