Unix Domain Socket IPC 流程与代码示例
以下内容为技术参考示例:
服务端的标准操作流程为:创建 socket 描述符,执行 bind 绑定地址,进行 listen 监听连接,随后通过 send/recv 进行数据收发,最后关闭连接 close。
客户端的标准操作流程为:创建 socket 描述符,执行 bind 绑定本地地址(可选但常见于特定场景),通过 connect 建立与服务端的连接,接着使用 send/recv 交换数据,完成后调用 close 关闭连接。
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#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 的实例代码详解,希望能为开发者提供帮助,欢迎持续关注本站获取更多技术资源。