写在前面:小生纯业余选手,开此博仅仅是为了积累,纯当笔记来用。如有看官光临小生博客,请不要相信我的代码是正确的。如果您发现了错误也恳请耽误您一点时间,请您在下面指出来,不胜感激!
  如果发现一些笔记的说法完全是错误的请建议我删除!
  有基于socket的进程通信方式,这种方式可以让两个不在同一台主机上的进程进行通信
  这里的通信方式与前几种有点不同,需要好好琢磨这种不同,方便以后学习网络编程。

 

<span style="font-size:18px;"><span style="font-family:SimSun;font-size:18px;">#include<sys/socket.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<linux/un.h>
#include<unistd.h>
int main()
{
char buf[256];
int fd = socket(AF_UNIX,SOCK_DGRAM,0);
if( fd == -1 )
{
printf("socket error:%m ");
exit(-1);
}else
{
printf("socket complete ");
}
struct sockaddr_un addr = {0};
addr.sun_family = AF_UNIX;
memcpy(addr.sun_path,"my.sock",strlen("my.sock"));
int r = bind( fd,reinterpret_cast<struct sockaddr*>(&addr),sizeof(addr) );
if( r == -1 )
{
printf("bind error:%m ");
exit(-1);
}else
{
printf("bind complete ");
}
while(1)
{
bzero(buf,sizeof(buf));
r = read(fd,buf,sizeof(buf));
buf[r] = '';
printf("%s ",buf);
}
close(fd);
unlink("my.sock");
return 0;
}
</span></span>