【Linux系统编程】进程间通信之无名管道

00. 目录

01. 管道概述

管道也叫无名管道,它是是 UNIX 系统 IPC(进程间通信) 的最古老形式,所有的 UNIX 系统都支持这种通信机制。

无名管道的特点

1、半双工,数据在同一时刻只能在一个方向上流动。

2、数据只能从管道的一端写入,从另一端读出。

3、写入管道中的数据遵循先入先出的规则。

4、管道所传送的数据是无格式的,这要求管道的读出方与写入方必须事先约定好数据的格式,如多少字节算一个消息等。

5、管道不是普通的文件,不属于某个文件系统,其只存在于内存中。

6、管道在内存中对应一个缓冲区。不同的系统其大小不一定相同。

7、从管道读数据是一次性操作,数据一旦被读走,它就从管道中被抛弃,释放空间以便写更多的数据。

8、管道没有名字,只能在具有公共祖先的进程(父进程与子进程,或者两个兄弟进程,具有亲缘关系)之间使用。

对于无名管道特点的理解,我们可以类比现实生活中管子,管子的一端塞东西,管子的另一端取东西。

无名管道是一种特殊类型的文件,在应用层体现为两个打开的文件描述符。
在这里插入图片描述

02. 管道创建函数

#include <unistd.h>

int pipe(int pipefd[2]);
功能:
    创建无名管道。

参数:
	pipefd :int 型数组的首地址,其存放了管道的文件描述符 pipefd[0]、pipefd[1]。
	
	当一个管道建立时,它会创建两个文件描述符 fd[0] 和 fd[1]。其中 fd[0] 固定用于读管道,而 fd[1] 固定用于写管道。一般文件 I / O 的函数都可以用来操作管道(lseek() 除外)。

返回值:
	成功:0
	失败:-1

下面我们写这个一个例子,子进程通过无名管道给父进程传递字符串数据

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define SIZE 64

int main(void)
{
    int fd[2];
    int i = 0;
    pid_t pid = -1;

    char buf[SIZE];

    //创建一个无名管道 用在具有共同祖先的进程
    if (pipe(fd) == -1)
    {
        perror("pipe"); 
        goto err0;
    }

    printf("fd[0]: %d fd[1]: %d\n", fd[0], fd[1]);


    //创建子进程
    pid = fork();
    if (-1 == pid)
    {
        perror("fork"); 
        goto err1;
    }
    else if (0 == pid)
    {
        while(1)
        {
            //子进程  写管道
            memset(buf, 0, SIZE); 
            sprintf(buf, "hello uplooking %d", i++);

            write(fd[1], buf, strlen(buf));

            sleep(1);

            if (i >= 10)
                break;
        }

        //关闭描述符
        close(fd[0]);
        close(fd[1]);

        exit(0);
    }
    else
    {
        //父进程 读管道
        while(1)
        {
            memset(buf, 0, SIZE); 

            if (read(fd[0], buf, SIZE) <= 0)
                break;

            printf("\033[31mbuf: %s\033[0m\n", buf); 
        }

        //关闭描述符
        close(fd[0]);
        close(fd[1]);
    }

    return 0;
err1:
    close(fd[0]);
    close(fd[1]);
err0:
    return 1;
}

测试结果:

deng@itcast:/mnt/hgfs/LinuxHome/code.bak2/4sys/4th/code$ gcc 17pipe.c 
deng@itcast:/mnt/hgfs/LinuxHome/code.bak2/4sys/4th/code$ ./a.out  
fd[0]: 3 fd[1]: 4
buf: hello uplooking 0
buf: hello uplooking 1
buf: hello uplooking 2
buf: hello uplooking 3
buf: hello uplooking 4
buf: hello uplooking 5
buf: hello uplooking 6

03. 管道的特性

每个管道只有一个页面作为缓冲区,该页面是按照环形缓冲区的方式来使用的。这种访问方式是典型的“生产者——消费者”模型。当“生产者”进程有大量的数据需要写时,而且每当写满一个页面就需要进行睡眠等待,等待“消费者”从管道中读走一些数据,为其腾出一些空间。相应的,如果管道中没有可读数据,“消费者” 进程就要睡眠等待,具体过程如下图所示:

在这里插入图片描述

默认的情况下,从管道中读写数据,最主要的特点就是阻塞问题(这一特点应该记住),当管道里没有数据,另一个进程默认用 read() 函数从管道中读数据是阻塞的。

测试代码:

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
 
int main(int argc, char *argv[])
{
	int fd_pipe[2] = {0};
	pid_t pid;
	
	if( pipe(fd_pipe) < 0 ){// 创建无名管道
		perror("pipe");
	}
	
	pid = fork(); // 创建进程
	if( pid < 0 ){ // 出错
		perror("fork");
		exit(-1);
	}
	
	if( pid == 0 ){ // 子进程
		
		_exit(0);
	}else if( pid > 0){// 父进程
	
		wait(NULL);	// 等待子进程结束,回收其资源
		
		char str[50] = {0};
		
		printf("before read\n");
		
		// 从管道里读数据,如果管道没有数据, read()会阻塞
		read(fd_pipe[0], str, sizeof(str));
		
		printf("after read\n");
		
		printf("str=[%s]\n", str); // 打印数据
	}
	
	return 0;
}

测试结果:

deng@itcast:/mnt/hgfs/LinuxHome/code.bak2$ gcc 1.c 
deng@itcast:/mnt/hgfs/LinuxHome/code.bak2$ ./a.out  
before read




04. 管道设置非阻塞

当然,我们编程时可通过 fcntl() 函数设置文件的阻塞特性。

设置为阻塞:fcntl(fd, F_SETFL, 0);
设置为非阻塞:fcntl(fd, F_SETFL, O_NONBLOCK);

测试代码:

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
 
int main(int argc, char *argv[])
{
	int fd_pipe[2] = {0};
	pid_t pid;
	
	if( pipe(fd_pipe) < 0 ){// 创建无名管道
		perror("pipe");
	}
	
	pid = fork(); // 创建进程
	if( pid < 0 ){ // 出错
		perror("fork");
		exit(-1);
	}
	
	if( pid == 0 ){ // 子进程
		
		sleep(3);
		
		char buf[] = "hello, tom";
		write(fd_pipe[1], buf, strlen(buf)); // 写数据
		
		_exit(0);
	}else if( pid > 0){// 父进程
	
		fcntl(fd_pipe[0], F_SETFL, O_NONBLOCK); // 非阻塞
		//fcntl(fd_pipe[0], F_SETFL, 0); // 阻塞
		
		while(1){
			char str[50] = {0};
			read( fd_pipe[0], str, sizeof(str) );//读数据
			
			printf("str=[%s]\n", str);
			sleep(1);
		}
	}
	
	return 0;
}

测试结果:

deng@itcast:/mnt/hgfs/LinuxHome/code.bak2$ gcc 1.c 
deng@itcast:/mnt/hgfs/LinuxHome/code.bak2$ ./a.out  
str=[]
str=[]
str=[]
str=[hello, tom]
str=[]
str=[]
str=[]
str=[]
str=[]

默认的情况下,从管道中读写数据,还有如下特性:

1)调用 write() 函数向管道里写数据,当缓冲区已满时 write() 也会阻塞。

测试代码如下:

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
 
int main(int argc, char *argv[])
{
	int fd_pipe[2] = {0};
	pid_t pid;
	
	char buf[1024] = {0};
	memset(buf, 'a', sizeof(buf)); // 往管道写的内容
	int i = 0;
	
	if( pipe(fd_pipe) < 0 ){// 创建无名管道
		perror("pipe");
	}
	
	pid = fork(); // 创建进程
	if( pid < 0 ){ // 出错
		perror("fork");
		exit(-1);
	}
	
	if( pid == 0 ){ // 子进程
		while(1){
			write(fd_pipe[1], buf, sizeof(buf));
			i++;
			printf("i ======== %d\n", i);
		}
		
		_exit(0);
	}else if( pid > 0){// 父进程
	
		wait(NULL);	// 等待子进程结束,回收其资源
	}
	
	return 0;
}

测试结果:

deng@itcast:/mnt/hgfs/LinuxHome/code.bak2$ gcc 1.c 
deng@itcast:/mnt/hgfs/LinuxHome/code.bak2$ ./a.out  
i ======== 1
i ======== 2
i ======== 3
i ======== 4
i ======== 5
i ======== 6
i ======== 7
i ======== 8
i ======== 9
i ======== 10
i ======== 11
i ======== 12
i ======== 13
i ======== 14
i ======== 15
i ======== 16
i ======== 17
i ======== 18
i ======== 19
i ======== 20
i ======== 21
i ======== 22
i ======== 23
i ======== 24
i ======== 25
i ======== 26
i ======== 27
i ======== 28
i ======== 29
i ======== 30
i ======== 31
i ======== 32
i ======== 33
i ======== 34
i ======== 35
i ======== 36
i ======== 37
i ======== 38
i ======== 39
i ======== 40
i ======== 41
i ======== 42
i ======== 43
i ======== 44
i ======== 45
i ======== 46
i ======== 47
i ======== 48
i ======== 49
i ======== 50
i ======== 51
i ======== 52
i ======== 53
i ======== 54
i ======== 55
i ======== 56
i ======== 57
i ======== 58
i ======== 59
i ======== 60
i ======== 61
i ======== 62
i ======== 63
i ======== 64

到了64没有打印,说明管道的缓冲区大小是64K

2)通信过程中,别的进程先结束后,当前进程读端口关闭后,向管道内写数据时,write() 所在进程会(收到 SIGPIPE 信号)退出,收到 SIGPIPE 默认动作为中断当前进程。

测试代码:

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
 
int main(int argc, char *argv[])
{
	int fd_pipe[2] = {0};
	pid_t pid;
	
	if( pipe(fd_pipe) < 0 ){// 创建无名管道
		perror("pipe");
	}
	
	pid = fork(); // 创建进程
	if( pid < 0 ){ // 出错
		perror("fork");
		exit(-1);
	}
	
	if( pid == 0 ){ // 子进程
		//close(fd_pipe[0]);
		
		_exit(0);
	}else if( pid > 0 ){// 父进程
	
		wait(NULL);	// 等待子进程结束,回收其资源
		
		close(fd_pipe[0]); // 当前进程读端口关闭
		
		char buf[50] = "12345";
		
		// 当前进程读端口关闭
		// write()会收到 SIGPIPE 信号,默认动作为中断当前进程
		write(fd_pipe[1], buf, strlen(buf));
		
		while(1);	// 阻塞
	}
	
	return 0;
}

测试结果:

deng@itcast:/mnt/hgfs/LinuxHome/code.bak2$ gcc 1.c 
deng@itcast:/mnt/hgfs/LinuxHome/code.bak2$ ./a.out 
deng@itcast:/mnt/hgfs/LinuxHome/code.bak2$ 

程序直接中断退出,没有任何结果。

05. 附录

5.1 参考博客:【Linux系统编程】进程间通信–无名管道(pipe)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值