Robby75
Robby75

Reputation: 3455

how to use a AF_UNIX socket without leaking resources?

I have a server that receives commands from various other local processes.

I chose the most simplest form (endless loop with accept-read), but here the socket-connections remain open and I soon run out of them (running on a virtual host). Then, on a client, socket() fails with the error message "Cannot allocate memory". (However memory is not the problem, it surely is some socket-limitation from the virtual host.)

I also tried to have the whole thing (unlink-socket-bind-accept-listen-read-close) in an endless loop, which also does not solve the problem. One of these commands seems to grab a socket-connection that never gets released. (Only killing and restarting the server process allows the clients to connect again) Using shutdown() before close() also does not help.

The type of the socket is AF_UNIX / SOCK_SEQPACKET.

How can I use a socket without leaking system ressources?

Edit: As requested the endless loop in the server:

while(1)
{
    unlink(SOCKET_FILE_PATH);       
    if((socket_fd = socket(AF_UNIX, SOCK_SEQPACKET, 0)) < 0)
    {
        perror("socket() failed");
        return 1;
    }
    if(bind(socket_fd, (const struct sockaddr *) &server_address, sizeof(server_address)) < 0)
    {
        close(socket_fd);
        perror("bind() failed");
        return 1;
    }
    listen(socket_fd, 10);
    newsockfd = accept(socket_fd, (struct sockaddr *)&cli_addr, &clilen);
    if (newsockfd < 0) 
    {
        perror("ERROR on accept");
        return 1;
    }
    bzero(buffer,256);
    n = read( newsockfd,buffer,255 );
    if (n < 0)
    {
        perror("ERROR reading from socket");
        return 1;
    }
    printf("buffer: \"%s\"\n",buffer);
    shutdown(socket_fd, SHUT_RDWR);
    close(socket_fd);
}

Upvotes: 0

Views: 217

Answers (1)

Martin James
Martin James

Reputation: 24897

Where do you close 'newsockfd'? Also, there is no guarantee that the buffer contains a null-terminated string, so calling printf(%s..) on it will likely segfault or some other UB.

Upvotes: 0

Related Questions