unix domain socket 是IPC通信的一种方式,可用于与管理进程间通信,同时由和网络socket统一,所以很好管理,使用还是比较多。现举个例子:
server.c
1 #include <stdio.h> 2 #include <string.h> 3 #include <unistd.h> 4 #include <stdlib.h> 5 #include <sys/types.h> 6 #include <sys/socket.h> 7 #include <sys/un.h> 8 #include <stddef.h> 9 10 #define SRC_ADDR "/var/run/uds_test.socket" 11 12 int main (int argc, char **argv) 13 { 14 int sockfd; 15 struct sockaddr_un src; 16 int ret; 17 18 unlink (SRC_ADDR); 19 sockfd = socket (AF_UNIX, SOCK_DGRAM, 0); 20 if (sockfd < 0) { 21 perror ("create socket failed"); 22 exit (EXIT_FAILURE); 23 } 24 25 memset (&src, 0, sizeof (src)); 26 src.sun_family = AF_UNIX; 27 strcpy (src.sun_path, SRC_ADDR); 28 int len; 29 len = offsetof (struct sockaddr_un, sun_path) + 30 sizeof (SRC_ADDR); 31 32 if (bind (sockfd, (struct sockaddr *)&src, len) < 0) { 33 perror ("bind socket failed"); 34 exit (EXIT_FAILURE); 35 } 36 37 size_t size = 0; 38 char buf[BUFSIZ] ={‘\0‘}; 39 for (;;) { 40 size = recvfrom (sockfd,buf, BUFSIZ,0, 41 NULL, NULL); 42 43 if (size > 0) 44 printf ("recv: %s\n", buf); 45 46 } 47 48 return 0; 49 }
client.c
#include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <stddef.h> #include <time.h> #define DST_ADDR "/var/run/uds_test.socket" int main (int argc, char **argv) { int sockfd; struct sockaddr_un dst; int ret; sockfd = socket (AF_UNIX, SOCK_DGRAM, 0); if (sockfd < 0) { perror ("create socket failed"); exit (EXIT_FAILURE); } memset (&dst, 0, sizeof (dst)); dst.sun_family = AF_UNIX; strcpy (dst.sun_path, DST_ADDR); int len; len = offsetof (struct sockaddr_un, sun_path) + sizeof (DST_ADDR); time_t t; char *str; for (;;) { t = time (NULL); str = ctime (&t); if (str == NULL) break; sendto (sockfd, str, strlen (str),0, (struct sockaddr *)&dst,len); sleep (1); } return 0; }
这个demo实现client端读取当前的时间,然后通过UDS发送给服务器端,结果如图所示:
一个简单的示例,希望能给你提供些思路
unix domain socket示例一(SOCK_DGRAM),布布扣,bubuko.com
unix domain socket示例一(SOCK_DGRAM)
原文:http://www.cnblogs.com/arnold0kang/p/3744823.html