国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 服務器 > Web服務器 > 正文

socket unix domain IPC的實例代碼

2024-09-01 13:49:54
字體:
來源:轉載
供稿:網友

僅供參考:

服務端:socket->bind->listen->send/recv->close

客戶端:socket->bind->connect->send/recv->close

#include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <fcntl.h> #include <sys/un.h> #include <pthread.h> #include <cstring> #include <cstdio> #include <unistd.h> #include <signal.h>  #define filename "test.socket"  void setnonblocking(int fd) {   fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK); }  void *client_func(void *arg) {   sleep(3);   int fd = socket(AF_UNIX, SOCK_STREAM, 0);   setnonblocking(fd);   sockaddr_un un;   memset(&un, 0, sizeof(un));   un.sun_family = AF_UNIX;   sprintf(un.sun_path, "file_%d.socket", (int)getpid());   unlink(un.sun_path);   socklen_t len = sizeof(un);   bind(fd, (sockaddr *)&un, sizeof(un));   strcpy(un.sun_path, filename);   int ret = connect(fd, (sockaddr *)&un, len);   if (ret == -1)   {     printf("connect server failed.../n");     close(fd);     return NULL;   }   char buf[256];   memset(buf, 0, sizeof(buf));   strcpy(buf, "hello world");   int n = send(fd, buf, strlen(buf)+1, 0);   printf("send data, %d bytes../n", n);   sleep(5);   close(fd);    return NULL; }  int main() {   unlink(filename);     signal(SIGPIPE, SIG_IGN);   int fd = socket(AF_UNIX, SOCK_STREAM, 0);   int yes = 1;   setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));   setnonblocking(fd);   sockaddr_un un;   memset(&un, 0, sizeof(un));   un.sun_family = AF_UNIX;   strcpy(un.sun_path, filename);   bind(fd, (sockaddr *)&un, sizeof(un));   listen(fd, 100);      pthread_t pid;   pthread_create(&pid, NULL, client_func, NULL);    sockaddr_un uu;   socklen_t len = sizeof(uu);    while (true)   {     memset(&uu, 0, len);     int newfd = accept(fd, (sockaddr *)&uu, &len);      if (newfd != -1)     {       setnonblocking(newfd);       printf("newfd = %d, path = %s/n", newfd, uu.sun_path);       char buf[512];       memset(buf, 0, sizeof(buf));       int n = recv(newfd, buf, 512,0);       printf("recv %d bytes, contents is %s/n", n, buf);     }     usleep(100000);   }      close(fd);    return 0; } 

以上就是小編為大家帶來的socket unix domain IPC的實例代碼全部內容了,希望大家多多支持VEVB武林網~

 

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 伊金霍洛旗| 南投市| 岚皋县| 巫山县| 丹东市| 固安县| 宁国市| 乌拉特中旗| 吉安县| 永清县| 奉贤区| 贵州省| 赤水市| 福贡县| 温州市| 来凤县| 壤塘县| 陇南市| 镇赉县| 交城县| 崇礼县| 集贤县| 东台市| 庄河市| 建德市| 青龙| 吐鲁番市| 瑞丽市| 和政县| 巢湖市| 富蕴县| 平山县| 宝丰县| 南宫市| 南安市| 武陟县| 册亨县| 长汀县| 康保县| 邢台县| 远安县|