#include #include #include #include #include #include #include #include #include #define handle_error(msg) do { perror(msg); exit(EXIT_FAILURE); } while(0) static int conn; int main(int argc, char *argv[]) { pid_t pid; char buf[64] = {0}; int sfd, cfd, ret; struct sockaddr_un addr; sfd = socket(AF_UNIX, SOCK_STREAM, 0); if (sfd == -1) handle_error ("Failed to create socket"); if (unlink ("/tmp/fd-pass.socket") == -1 && errno != ENOENT) handle_error ("Removing socket file failed"); memset(&addr, 0, sizeof(struct sockaddr_un)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, "/tmp/fd-pass.socket", sizeof(addr.sun_path) - 1); if (bind(sfd, (struct sockaddr *) &addr, sizeof(struct sockaddr_un)) == -1) handle_error ("Failed to bind to socket"); if (listen(sfd, 5) == -1) handle_error ("Failed to listen on socket"); while (1) { cfd = accept(sfd, NULL, NULL); if (cfd == -1) handle_error ("Failed to accept incoming connection"); conn++; fprintf(stdout, "%d CONNECTION/S ESTABLISHED\n", conn); pid = fork(); if (pid == -1) { handle_error ("Failed to fork after accepting connection"); } else if (pid == 0) { if (close(sfd) == -1) handle_error ("Failed to close server socket in child"); ret = recv (cfd, buf, 64, 0); if (ret == -1) handle_error ("Failed to receive data from client in child"); ret = send (cfd, buf, ret, 0); if (ret == -1) handle_error ("Failed to send data to client in child"); if (close(cfd) == -1) handle_error ("Failed to close server socket in child"); exit(0); } waitpid (-1, NULL, 0); if (close(cfd) == -1) handle_error ("Failed to close client socket"); } return 0; }