#include #include #include #include #include #include #include #include #include #include #define SOCKNAME "sock_unix" int main() { int fd; struct sockaddr_un sunx; pid_t pid; ssize_t len; char buf[BUFSIZ]; memset(&sunx, 0, sizeof(sunx)); sunx.sun_family = AF_UNIX; strncpy (sunx.sun_path, SOCKNAME, sizeof(sunx.sun_path) -1 ); pid = fork(); if (pid) { int fd1; fd = socket(AF_UNIX, SOCK_STREAM, 0); if (fd < 0) { perror("socket"); goto end_server; } if (bind(fd, (struct sockaddr *)&sunx, sizeof(sunx)) < 0) { perror("bind"); goto end_server; } if (listen(fd, 1) < 0) { perror("listen"); goto end_server; } fd1 = accept(fd, 0, 0); if (fd1 < 0) { perror("accept"); goto end_server; } while ((len = read(fd1, buf, sizeof(buf))) > 0) { buf[len] = '\0'; printf("%d: %s\n", len, buf); } close(fd1); end_server: close(fd); kill(pid, SIGTERM); wait(NULL); if (unlink(SOCKNAME) < 0) { perror("unlink"); } } else { usleep(100000); fd = socket(AF_UNIX, SOCK_STREAM, 0); if (fd < 0) { perror("socket"); goto end_client; } if (connect(fd, (struct sockaddr *)&sunx, sizeof(sunx)) < 0) { perror("connect"); goto end_client; } write(fd, "1234567890", 10); end_client: close(fd); } return 0; }