进程间通信---无名管道、有名管道、信号通信、共享内存、消息队列、信号灯、socket
数据库:动态库.os 静态库.a /lib /usr/lib
不同1. .a .so
2.使用时刻不同 静态编译 动态运行
3.可移植性 静态可移植
通信领域的几个概念:
单工通信:数据的传送方向为单向
半双工通信:数据的传送方向为双向,但不同时
全双工通信:数据的传送方向为双向且同时
1.无名管道
无名管道是用pipe创建的一个内核文件,用于具有亲缘关系的进程间的通信。
int pipe(int pipefd[2]);
pipefd[2]:数组,fd[0]用来标识读管道文件
fd[1]用来标识写管道文件
返回值:0 成功;-1 失败
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#define BUF_SIZE 20
int main()
{
//1.pipe
int fd[2] = {0};
if(0 != pipe(fd))
{
printf("create pipr error!!\r\n");
return -1;
}
printf("1:create pipe ok!\r\n");
//2.fork
pid_t pid = -1;
pid = fork();
if(-1 == pid)
{
return -1;
}
char buf[BUF_SIZE] = {0};
if(0 == pid)
{
//child write
close(fd[0]);
printf("child process!\r\n");
strcpy(buf,"child to parent");
write(fd[1],buf,BUF_SIZE);
}
else
{
//parent read
close(fd[1]);
printf("parent process!\r\n");
read(fd[0],buf,BUF_SIZE);
printf("parent read:%s\r\n",buf);
}
}
特点:
1.只能用于具有亲缘关系的进程间通信
2.是一种单工通信模式(理论上是双工的,但是通信双方的收发顺序不好控制,通常用作单工)
3.无名管道的数据存放在内存中,管道中的数据读走后就不存在了,无名管道只存在于内核中,在文件系统中不可见
2.有名管道
有名管道是用mkfifo创建的一个内核文件,用于任意两个进程之间的通信,管道文件在文件系统中可见。
int mkfifo(const char *pathname, mode_t mode);
作用:创建一个有名管道文件
*pathname:有名管道文件的名称
mode:文件权限
返回值:0 成功; -1 失败
ret = mkfifo("fifo",0666);
if(ret<0&&EEXIST!=errno)-->创建文件失败并且该文件不存在
{
return -1;//创建文件失败
}
创建文件失败但是该文件存在==>创建文件成功
A:
1.mkfifo ---> 有名称
2.open
3.write
B:
1.mkfifo
2.open
3.read
单工
#include<stdio.h>
//#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<errno.h>
#include<fcntl.h>
#include<string.h>
#define BUF_SIZE 20
int mian()
{
//1.mkfifo
int ret = -1;
ret = mkfifo("fifo",0666);
if(ret < 0&& EEXIST != errno)
{
return -1;
}
printf("create fifo ok!---\r\n");
//2.open
int fd = open("fifo",O_WRONLY,0666);
if(-1 == fd)
{
return -1;
}
printf("2:open fifo ok!--------\r\n");
//3.write
cha