MinGW: Add missing file mode bit defines
[git/dscho.git] / unix-socket.c
blobcf9890f57c17046f3b445a9dddfafae19526bc45
1 #include "cache.h"
2 #include "unix-socket.h"
4 static int unix_stream_socket(void)
6 int fd = socket(AF_UNIX, SOCK_STREAM, 0);
7 if (fd < 0)
8 die_errno("unable to create socket");
9 return fd;
12 static void unix_sockaddr_init(struct sockaddr_un *sa, const char *path)
14 int size = strlen(path) + 1;
15 if (size > sizeof(sa->sun_path))
16 die("socket path is too long to fit in sockaddr");
17 memset(sa, 0, sizeof(*sa));
18 sa->sun_family = AF_UNIX;
19 memcpy(sa->sun_path, path, size);
22 int unix_stream_connect(const char *path)
24 int fd;
25 struct sockaddr_un sa;
27 unix_sockaddr_init(&sa, path);
28 fd = unix_stream_socket();
29 if (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
30 close(fd);
31 return -1;
33 return fd;
36 int unix_stream_listen(const char *path)
38 int fd;
39 struct sockaddr_un sa;
41 unix_sockaddr_init(&sa, path);
42 fd = unix_stream_socket();
44 if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
45 unlink(path);
46 if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
47 close(fd);
48 return -1;
52 if (listen(fd, 5) < 0) {
53 close(fd);
54 return -1;
57 return fd;