unix domain socket 例子
时间: 2023-12-01 08:04:52 浏览: 162
Socket例子
下面是一个使用 Unix Domain Socket 进行进程间通信的简单例子:
服务端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#define SOCKET_PATH "/tmp/mysocket"
int main(void) {
int server_fd, client_fd;
struct sockaddr_un server_addr, client_addr;
socklen_t client_len;
// 创建 socket
server_fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (server_fd == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
// 绑定地址
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sun_family = AF_UNIX;
strncpy(server_addr.sun_path, SOCKET_PATH, sizeof(server_addr.sun_path) - 1);
unlink(SOCKET_PATH);
if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("bind");
exit(EXIT_FAILURE);
}
// 监听端口
if (listen(server_fd, 5) == -1) {
perror("listen");
exit(EXIT_FAILURE);
}
printf("Listening on socket %s\n", SOCKET_PATH);
while (1) {
// 接受连接
client_len = sizeof(client_addr);
client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_len);
if (client_fd == -1) {
perror("accept");
continue;
}
printf("Accepted connection\n");
// 发送欢迎消息
if (write(client_fd, "Welcome to my server", 21) == -1) {
perror("write");
close(client_fd);
continue;
}
// 关闭连接
close(client_fd);
}
return 0;
}
```
客户端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#define SOCKET_PATH "/tmp/mysocket"
int main(void) {
int server_fd;
struct sockaddr_un server_addr;
char buf[1024];
ssize_t n;
// 创建 socket
server_fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (server_fd == -1) {
perror("socket");
exit(EXIT_FAILURE);
}
// 连接到服务端
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sun_family = AF_UNIX;
strncpy(server_addr.sun_path, SOCKET_PATH, sizeof(server_addr.sun_path) - 1);
if (connect(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("connect");
exit(EXIT_FAILURE);
}
// 读取欢迎消息
n = read(server_fd, buf, sizeof(buf));
if (n == -1) {
perror("read");
exit(EXIT_FAILURE);
}
printf("Received: %.*s\n", (int)n, buf);
// 关闭连接
close(server_fd);
return 0;
}
```
以上代码演示了一个简单的 Unix Domain Socket 客户端和服务端的通信过程。服务端创建了一个 Unix Domain Socket 并监听客户端的连接请求,客户端连接到服务端并发送一个请求,服务端收到请求后向客户端发送一个欢迎消息,然后关闭连接。通信过程中使用了 read 和 write 函数进行数据传输。
阅读全文