1.unix域协议
IPC方式之一
socket 进行进程间通信
利用 socket编程接口 来实现 本地进程间通信
有自己协议簇
unix域协议:AF_UNIX / AF_LOCAL
socket套接字
SOCK_STREAM 面向字节流 ——》tcp
SOCK_DGRAM 面向数据报 ——》UDP
unix域协议 编程接口及流程和 ipv4 协议族一样
但是unix域协议的网络地址
#include <sys/un.h>
struct sockaddr_un
{
sa_family_t sun_family; //AF_LOCAL / AF_UNIX
char sun_path[1024];//unix域协议的地址,以'\0'结束的本地文件
//系统中的绝对路径名 "/tmp/xxxx.socket"
//不需要存在
}
unix域协议 ——》UDP
每个进程都有属于自己一个 "unix域协议的网络地址(本地的路径名)"
sendto
recvfrom
模板: IPC_unix.c IPC_unix.h main.c
IPC_unix.c
#include "IPC_unix.h"
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int Create_UNIX_Socket_UDP(const char *LocalSocketPath)
{
//1.创建套接字
int sock = socket(AF_UNIX,SOCK_DGRAM,0);
if(-1 == sock)
{
perror("socket fail");
}
//2.绑定地址
struct sockaddr_un local;
local.sun_family = AF_UNIX;//指定协议族
strcpy(local.sun_path,LocalSocketPath);
int res = bind(sock,(struct sockaddr*)&local,sizeof(local));
if(-1 == res)
{
//失败,关闭套接字 返回-1;
perror("bind fail");
close(sock);
return -1;
}
//返回套接字
return sock;
}
void Unlink_UNIX_Socket(const char *LocalSocketPath)
{
unlink(LocalSocketPath);
}
int Send_UNIX_Data_UDP(int sockfd,const char *DestSocketPath,char* data,int dataLen)
{
struct sockaddr_un DestAddr;
DestAddr.sun_family = AF_UNIX;//指定协议族
strcpy(DestAddr.sun_path,DestSocketPath);
int res = sendto(sockfd, data, dataLen,0,(struct sockaddr *)&DestAddr,sizeof(DestAddr));
if(-1 == res)
{
perror("send data fail");
}
return res;
}
int Recv_UNIX_Data_UDP(int socket,char *data,int dataLen)
{
int len = recvfrom(socket,data,dataLen,0,NULL,NULL);
if(-1 == len)
{
perror("recv data fail");
}
return len;
}
IPC_unix.h
#ifndef __IPC_UNIX_H__
#define __IPC_UNIX_H__
int Create_UNIX_Socket_UDP(const char *LocalSocketPath);
void Unlink_UNIX_Socket(const char *LocalSocketPath);
int Send_UNIX_Data_UDP(int socket,const char *DestSocketPath,char* data,int dataLen);
int Recv_UNIX_Data_UDP(int socket,char *data,int dataLen);
#endif
main.c
#include "IPC_unix.h"
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int pid = fork();
int sock;
if(pid == 0)//子进程
{
char buf[256] = {0};
Unlink_UNIX_Socket("/home/china/2.socket");
sock = Create_UNIX_Socket_UDP("/home/china/2.socket");
if(-1 == sock)
{
perror("Create_UNIX_Socket_UDP fail");
close(sock);
return -1;
}
Recv_UNIX_Data_UDP(sock,buf,255);
printf("father:%s\n",buf);
}
else if(pid > 0)//父进程
{
sleep(1);
char buf[256] = {"欢迎光临!!!"};
Unlink_UNIX_Socket("/home/china/1.socket");
sock = Create_UNIX_Socket_UDP("/home/china/1.socket");
if(-1 == sock)
{
perror("Create_UNIX_Socket_UDP fail");
close(sock);
return -1;
}
Send_UNIX_Data_UDP(sock,"/home/china/2.socket",buf,strlen(buf));
}
else
{
perror("fork fail");
}
close(sock);
return 0;
}