Skip to content
The Chat Archive
mistral-medium-2505· Mistral AI LMArena Human Preference 140K

How to use unix sockets for two programs to communicate with a third one that acts as a…

  1. User

    How to use unix sockets for two programs to communicate with a third one that acts as a server ?

  2. Assistant

    Using Unix domain sockets for inter-process communication (IPC) between multiple programs is a common and efficient method. Here's a step-by-step guide on how to set this up with one server and two client programs:


    1. Overview

    • Server Program: Listens on a Unix socket and handles requests from clients.
    • Client Programs: Connect to the server via the Unix socket and send/receive data.

    2. Server Program (C Example)

    The server creates a Unix socket, binds it to a file, listens for connections, and handles client requests.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    #include <sys/socket.h>
    #include <sys/un.h>
    #include <errno.h>
    
    #define SOCKET_PATH "/tmp/my_unix_socket"
    
    int main() {
        int server_fd, client_fd;
        struct sockaddr_un server_addr, client_addr;
        socklen_t client_len;
        char buffer[1024];
    
        // Create a Unix socket
        server_fd = socket(AF_UNIX, SOCK_STREAM, 0);
        if (server_fd == -1) {
            perror("socket");
            exit(EXIT_FAILURE);
        }
    
        // Configure server address
        memset(&server_addr, 0, sizeof(server_addr));
        server_addr.sun_family = AF_UNIX;
        strncpy(server_addr.sun_path, SOCKET_PATH, sizeof(server_addr.sun_path) - 1);
    
        // Remove old socket file if it exists
        unlink(SOCKET_PATH);
    
        // Bind the socket to the file
        if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
            perror("bind");
            close(server_fd);
            exit(EXIT_FAILURE);
        }
    
        // Listen for connections
        if (listen(server_fd, 5) == -1) {
            perror("listen");
            close(server_fd);
            exit(EXIT_FAILURE);
        }
    
        printf("Server listening on %s...\n", SOCKET_PATH);
    
        while (1) {
            // Accept a client connection
            client_len = sizeof(client_addr);
            client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_len);
            if (client_fd == -1) {
                perror("accept");
                continue;
            }
    
            // Read data from the client
            ssize_t bytes_read = read(client_fd, buffer, sizeof(buffer) - 1);
            if (bytes_read == -1) {
                perror("read");
                close(client_fd);
                continue;
            }
    
            buffer[bytes_read] = '\0';
            printf("Received: %s\n", buffer);
    
            // Send a response back
            const char *response = "Message received by server!";
            write(client_fd, response, strlen(response));
    
            close(client_fd);
        }
    
        close(server_fd);
        unlink(SOCKET_PATH);
        return 0;
    }
    

    3. Client Program (C Example)

    Each client connects to the server's Unix socket and sends a message.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    #include <sys/socket.h>
    #include <sys/un.h>
    #include <errno.h>
    
    #define SOCKET_PATH "/tmp/my_unix_socket"
    
    int main() {
        int sock_fd;
        struct sockaddr_un server_addr;
        char buffer[1024];
    
        // Create a Unix socket
        sock_fd = socket(AF_UNIX, SOCK_STREAM, 0);
        if (sock_fd == -1) {
            perror("socket");
            exit(EXIT_FAILURE);
        }
    
        // Configure server address
        memset(&server_addr, 0, sizeof(server_addr));
        server_addr.sun_family = AF_UNIX;
        strncpy(server_addr.sun_path, SOCKET_PATH, sizeof(server_addr.sun_path) - 1);
    
        // Connect to the server
        if (connect(sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
            perror("connect");
            close(sock_fd);
            exit(EXIT_FAILURE);
        }
    
        // Send a message to the server
        const char *message = "Hello from client!";
        write(sock_fd, message, strlen(message));
    
        // Read the server's response
        ssize_t bytes_read = read(sock_fd, buffer, sizeof(buffer) - 1);
        if (bytes_read == -1) {
            perror("read");
            close(sock_fd);
            exit(EXIT_FAILURE);
        }
    
        buffer[bytes_read] = '\0';
        printf("Server response: %s\n", buffer);
    
        close(sock_fd);
        return 0;
    }
    

    4. Steps to Run the Programs

    1. Compile the server and clients:

      gcc server.c -o server
      gcc client.c -o client
      
    2. Run the server first (it must be running before clients connect):

      ./server
      
    3. Run the clients in separate terminals:

      ./client
      
    4. Observe the communication:

      • The client sends a message to the server.
      • The server receives it, prints it, and sends a response back.
      • The client prints the server's response.

    5. Key Points

    • Socket File: The Unix socket is represented by a file (/tmp/my_unix_socket in this example). Ensure the server removes this file on exit (unlink).
    • Concurrency: The server handles one client at a time. For multiple clients, use fork() or threads.
    • Error Handling: Always check for errors in socket operations.
    • Permissions: Ensure the socket file has the correct permissions for clients to access it.

    6. Extending to Multiple Clients

    To handle multiple clients concurrently, modify the server to fork a new process for each client:

    while (1) {
        client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_len);
        if (client_fd == -1) {
            perror("accept");
            continue;
        }
    
        pid_t pid = fork();
        if (pid == 0) {  // Child process
            close(server_fd);  // Child doesn't need the server socket
            handle_client(client_fd);
            exit(0);
        } else if (pid > 0) {  // Parent process
            close(client_fd);  // Parent doesn't need the client socket
        } else {
            perror("fork");
        }
    }
    

    This setup allows two or more client programs to communicate with a single server program using Unix domain sockets.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.