#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#define SOCKET_PATH "/tmp/example_socket"
int main() {
int server_fd, client_fd;
struct sockaddr_un address;
int address_length = sizeof(address);
char buffer[1024];
// 创建一个本地socket
if ((server_fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
// 设置地址并绑定到socket
address.sun_family = AF_UNIX;
strcpy(address.sun_path, SOCKET_PATH);
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) == -1) {
perror("bind");
exit(1);
}
// 监听客户端连接请求
if (listen(server_fd, 5) == -1) {
perror("listen");
exit(1);
}
// 接受客户端连接
if ((client_fd = accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&address_length)) == -1) {
perror("accept");
exit(1);
}
// 接收客户端消息
ssize_t bytes_received = recv(client_fd, buffer, sizeof(buffer), 0);
if (bytes_received == -1) {
perror("recv");
exit(1);
}
// 打印接收到的消息
printf("Received message: %s\n", buffer);
// 关闭socket
close(client_fd);
close(server_fd);
unlink(SOCKET_PATH); // 删除socket文件
return 0;
}
这段代码展示了如何在Linux环境下使用本地socket实现进程间通信。它创建了一个服务器端socket,绑定到一个路径,监听连接请求,接受连接,并接收一条消息。代码简洁,注重于展示核心功能,并包含了错误处理。