实例:
service.c
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/un.h>
#include <string>
#include <iostream>
int num_reverse(int num)
{
int S=0,sum=0;
while(num)
{
S=num%10;
sum=10*sum+S;
num = num / 10;
}
return sum;
}
static std::string getProcessName(void)
{
char name[256];
int rval = readlink("/proc/self/exe", name, sizeof(name)-1);
if (rval < 0)
return std::string();
name[rval] = '\0';
return std::string(strrchr(name, '/') + 1);
}
int main()
{
int num;
char socketPath[256];
sprintf(socketPath, "/tmp/socket.dbg.%s", getProcessName().c_str());
printf("socketPath:%s\n", socketPath);
/* 断开之前的socket文件 */
unlink(socketPath);
/* 创建一个socket */
int server_sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
struct sockaddr_un server_addr;
server_addr.sun_family = AF_UNIX;
strcpy(server_addr.sun_path, socketPath);
/* 与本地文件进行绑定 */
bind(server_sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
/* 监听 */
int ret = listen(server_sockfd, 10);
if(ret < 0);
{
perror("Listen failed");
}
int client_sockfd;
struct