【系统编程】进程间通信--管道(无名管道、有名管道)

linux系统编程大纲
1. 进程概念、进程诞生与死亡、进程函数接口、进程意义。
2. 进程通信方式,有名管道、无名管道、信号、消息队列、共享内存、信号量。
3. 进程信号集、如何设置阻塞属性。
4. 线程概念,线程与进程区别?线程诞生与死亡,函数接口。
5. 线程同步互斥方式,有名信号量,无名信号量,互斥锁,读写锁,条件变量。
6. 拓展 -> 线程池  -> 同时处理多个任务。


一、无名管道

1. 什么是无名管道?作用范围是怎样的?
       无名管道其实是一个数组来的,里面存放着读端与写端的文件描述符。作用范围有亲缘关系的两个进程。

2. 如何初始化无名管道?  -> pipe()  -> man 2 pipe
功能:create pipe
使用格式:

   #include <unistd.h>
   int pipe(int pipefd[2]);

    pipefd: 具有两个int类型成员的数组的首元素地址。

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

例子:
int fd[2];
pipe(fd);  -> 结果: fd[0]->读端  fd[1]->写端

例题: 实现使用无名管道,使得父子进程之间通信。

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

int main()
{
	int ret;
	pid_t x;
	int fd[2] = {0};  //fd[0] = 0  fd[1] = 0
	ret = pipe(fd);  
	if(ret != 0)
	{
		printf("pipe error!\n");
	}
	
	printf("fd[0] = %d\n",fd[0]);
	printf("fd[1] = %d\n",fd[1]);
	
	x = fork();
	if(x > 0)
	{
		char buf[10];
		read(fd[0],buf,sizeof(buf));
		printf("buf:%s\n",buf);
		
		wait(NULL);
		exit(0);
	}
	
	if(x == 0)
	{
		char buf[10] = "hello";
		write(fd[1],buf,strlen(buf));
		exit(0);
	}

	return 0;
}

二、有名管道

1. 什么是有名管道?作用范围是什么?
     有名管道是一个文件,作用范围是整个系统中任意的两个进程!

2. 如何在linux下创建一个管道文件?  ->  mkfifo()  -> man 3 mkfifo
功能:make a FIFO special file  -> 管道文件是一种特殊的文件,不同于普通文件。
使用格式:
        #include <sys/types.h>
        #include <sys/stat.h>

       int mkfifo(const char *pathname, mode_t mode);

     参数: pathname:需要创建的管道文件的路径
                 mode:八进制权限

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

 例题: 实现1.c文件发送数据给2.c

1.c  ->读端
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

int main()
{
	umask(0000);
	
	int ret = mkfifo("/home/gec/test_fifo",0777);
	if(ret == -1)
	{
		printf("mkfifo error!\n");
	}
	
	int fd = open("/home/gec/test_fifo",O_RDWR);
	if(fd < 0)
	{
		printf("open error!\n");
	}
	
	char buf[100] = {0};
	read(fd,buf,sizeof(buf));
	printf("from fifo:%s",buf);
	
	close(fd);
	
	return 0;
}
2.c写端
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main()
{
	int fd = open("/home/gec/test_fifo",O_RDWR);
	if(fd < 0)
	{
		printf("open error!\n");
	}
	
	char buf[50] = {0};
	fgets(buf,50,stdin); //最多从键盘中获取50个字节  -> 包含\n在内
	write(fd,buf,strlen(buf));
	close(fd);
	return 0;
}
发布了64 篇原创文章 · 获赞 82 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_40602000/article/details/101198954
今日推荐