1、IPC 进程间通信
(1)pipe管道 半双工 ps_grep
(2)fifo有名管道
(3)mmap文件映射共享IO --速度最快
(4)本地socket套接字 --最稳定
(5)信号 --携带信息量最小
(6)共享内存
(7)消息队列
本地套接字是 IPC,也就是本地进程间通信的一种实现方式。除了本地套接字以外,其它技术,诸如管道、共享消息队列等也是进程间通信的常用方法,但因为本地套接字开发便捷,接受度高,所以普遍适用于在同一台主机上进程间通信的各种场景。
server.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/un.h>
int main(int argc, const char* argv[])
{
int lfd = socket(AF_LOCAL, SOCK_STREAM, 0);
if(lfd == -1)
{
perror("socket error");
exit(1);
}
// 如果套接字文件存在, 删除套接字文件
unlink("server.sock");
// 绑定
struct sockaddr_un serv;
serv.sun_family = AF_LOCAL;
strcpy(serv.sun_path, "server.sock");
int ret = bind(lfd, (struct sockaddr*)&serv, sizeof(serv));
if(ret == -1)
{
perror("bind error");
exit(1);
}
// 监听
ret = listen(lfd, 36);
if(ret == -1)
{
perror("listen error");
exit(1);
}
// 等待接收连接请求
struct sockaddr_un client;
socklen_t len = sizeof(client);
int cfd = accept(lfd, (struct sockaddr*)&client, &len);
if(cfd == -1)
{
perror("accept error");
exit(1);
}
printf("======client bind file: %s\n", client.sun_path);
// 通信
while(1)
{
char buf[1024] = {0};
int recvlen = recv(cfd, buf, sizeof(buf), 0);
if(recvlen == -1)
{
perror("recv error");
exit(1);
}
else if(recvlen == 0)
{
printf("clietn disconnect ....\n");
close(cfd);
break;
}
else
{
printf("recv buf: %s\n", buf);
send(cfd, buf, recvlen, 0);
}
}
close(cfd);
close(lfd);
return 0;
}
client.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/un.h>
int main(int argc, const char* argv[])
{
int fd = socket(AF_LOCAL, SOCK_STREAM, 0);
if(fd == -1)
{
perror("socket error");
exit(1);
}
unlink("client.sock");
// ================================
// 给客户端绑定一个套接字文件
struct sockaddr_un client;
client.sun_family = AF_LOCAL;
strcpy(client.sun_path, "client.sock");
int ret = bind(fd, (struct sockaddr*)&client, sizeof(client));
if(ret == -1)
{
perror("bind error");
exit(1);
}
// 初始化server信息
struct sockaddr_un serv;
serv.sun_family = AF_LOCAL;
strcpy(serv.sun_path, "server.sock");
// 连接服务器
connect(fd, (struct sockaddr*)&serv, sizeof(serv));
// 通信
while(1)
{
char buf[1024] = {0};
fgets(buf, sizeof(buf), stdin);
send(fd, buf, strlen(buf)+1, 0);
// 接收数据
recv(fd, buf, sizeof(buf), 0);
printf("recv buf: %s\n", buf);
}
close(fd);
return 0;
}