remove previous socket unlink SOCKET_PATH create new socket int sd soc

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// remove previous socket
unlink(SOCKET_PATH);
// create new socket
int sd = socket(AF_UNIX, SOCK_STREAM, 0);
if (sd < 0) {
syslog(LOG_ERR, "Socket failed: %s", strerror(errno));
exit(-1);
}
struct sockaddr_un serveraddr;
memset(&serveraddr, 0, sizeof(serveraddr));
serveraddr.sun_family = AF_UNIX;
strcpy(serveraddr.sun_path, SOCKET_PATH);
int res = bind(sd, (struct sockaddr*)&serveraddr, sizeof(serveraddr));
if (res < 0) {
syslog(LOG_ERR, "Socket bind failed: %s", strerror(errno));
exit(-1);
}
// change access rights
res = chmod(SOCKET_PATH, S_IRWXU | S_IRWXG | S_IRWXO);
if (res < 0) {
syslog(LOG_ERR, "Change access rights failed: %s", strerror(errno));
exit(-1);
}
// listen for incoming connections
res = listen(sd, 10);
if (res < 0) {
syslog(LOG_ERR, "Listen connections failed: %s", strerror(errno));
exit(0);
}
// accept and handle connections
while(1){
int cd = accept(sd, NULL, NULL);
if (cd < 0) {
syslog(LOG_WARNING, "Accept connection failed: %s", strerror(errno));
sleep(1);
}
handle(cd);
}