socket unix domain IPC的實例代碼
僅供參考:
服務(wù)端: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;
}
以上就是小編為大家?guī)淼膕ocket unix domain IPC的實例代碼全部內(nèi)容了,希望大家多多支持腳本之家~
相關(guān)文章
使用Apache搭建http服務(wù)器實現(xiàn)CGI功能
專門處理 HTTP 請求的服務(wù)器,也被稱為 Web 服務(wù)器, 常用的 Web 服務(wù)器有 Apache和 Nginx ,當(dāng)然幾大巨頭五聯(lián)網(wǎng)公司也都有其獨自研發(fā)的 Web 服務(wù)器,比如阿里巴巴的Tengine, 這篇文章主要介紹了使用Apache搭建http服務(wù)器,實現(xiàn)CGI,需要的朋友可以參考下2024-07-07
ubuntu16.10安裝docker17.03.0-ce并配置國內(nèi)源和加速器
這篇文章主要介紹了ubuntu16.10安裝docker17.03.0-ce并配置國內(nèi)源和加速器,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-05-05
Linux運維基礎(chǔ)httpd靜態(tài)網(wǎng)頁教程
這篇文章主要介紹了Linux運維基礎(chǔ)中怎樣制作httpd靜態(tài)網(wǎng)頁,附含源碼及圖片示例,有需要的朋友可以借鑒參考下,希望可以有所幫助,祝進(jìn)步2021-09-09
redhat Server release 5.2 安裝配置簡明教程
系統(tǒng)安裝:系統(tǒng)安裝采用光盤安裝,以前一直從USB移動硬盤安裝,前幾天心血來潮,刻成了DVD,以示嚴(yán)肅和一切從頭開始,呵呵。2009-08-08
在Linux服務(wù)器上安裝 memcached的基本操作
本文分步驟給大家詳細(xì)介紹了linux服務(wù)器上安裝memcached的操作方法,非常不錯,需要的朋友參考下吧2016-12-12
Linux使用sosreport實現(xiàn)生成系統(tǒng)報告
sosreport?命令是許多?Linux?發(fā)行版上可用的工具,特別是基于?Red?hat?的系統(tǒng),下面我們來看看如何使用sosreport實現(xiàn)生成系統(tǒng)報告吧2025-02-02

