csocketsc++11tcpbroken-pipe

How to reuse open client connection with forked child process on the server (TCP/IP Socket)


I want the client to communicate with the server using TCP/IP socket connection. When the connection is accepted on the server side, the child process is created. This child process read and processes incoming data. I thought, that when I do subsequent writes from the client, on the open connection, that the server side will do forking again, if the doSomething process has already exited. However what happening is, that the 2nd client write (TEST2) writes to a socket and:

a) the write indicates no error, but the server is not receiving anything or

b) exception Broken pipe

I have the pseudo code like this:

Client socket side:
{

    socketFD = socket(AF_INET, SOCK_STREAM, 0);
    connect(socketFD, (struct sockaddr *) &serv_addr, sizeof(sockaddr));
    write(socketFD, “TEST1”, strlen(“TEST1”));
    …….
    write(socketFD, “TEST2”, strlen(“TEST2”)); // error: Broken pipe

    .....
    close(sfd);

}

Server socket side: doSomething is running on a forked child process:

void doSomething(int socket)
{  

    int n;
    const int bufferSize = 1025;
    char buffer[1025];

    bzero(buffer,bufferSize);
    n = read(sock,buffer,bufferSize-1);

}

The write for “TEST2” will fail with the message “broken pipe”. This is probably because the doSomething has finished. The question is:

  1. how can I keep the forked (child) process doSomething listen after all (TEST1) data has been received and processed by the doSomething?
  2. if I keep doSomething continuously listen, how can I stop doSomething, if the client closes connection?

Solution

  • void doSomething(int socket)
    {  
    
        int n;
        char buffer[1024];
        do
        {
            //Normally your process will be blocked here until it receives some data from the client.
            //The socket must be under the blocking mode;
            n = read(sock,buffer,sizeof(buffer));
            ...do something with the buffer;
        }while(n>0);
    }