简体   繁体   中英

C++ - AF_UNIX socket hangs

I'm currently trying to get a client/daemon communication via an AF_UNIX socket up and running.

At the moment the client successfully sends a message, the daemon receives and processes it and then should send the message back.
Well, that's where the problem is. As soon as the daemon tries to send the message back nothing happens, the client hangs, trying to read a message, and if I kill the client the daemon dies with it.

Following is the daemon code:

//successful call to accept, I have a file descriptor now...
int c = 0;
while((c = recv(fd, (char*)&buf[0], bufferSize, 0)))
{
    if(c == -1 || c == 0)
        break;
    tmp.append(buf.begin(), buf.begin()+c);
}

writeLog(tmp);
tmp = evaluateMsg(tmp);
writeLog(tmp);

//I assume this send call is hanging
if(send(fd, tmp.c_str(), tmp.size(), 0) < 0)
    writeLog("Could not write message back!");

close(fd);

And this is the client code:

//connect(); is successful
//send(); as well - the recv(); call is hanging forever
while((c = recv(sockfd, (char*)&buf[0], 1024, 0)))
{
    if(c == -1)
    {
       cout<<"Error";
       break;
    }   
    else if(c == 0)
        break;
    tmp.append(buf.begin(), buf.begin()+c);
}

Please note that the code is heavily cut down for the sake of simplicity and readability (especially the code to daemonize and create the actual AF_UNIX socket (which are both successful)).

UPDATE:

I could verify that the client-side recv() call is never returning, which means that the daemon-side send() call is hanging. Why?

I don't see any reason that the daemon side recv() loop will end. Why would recv() return 0 or -1 if the socket is still open?

You should understand when the client finished sending data on the application level, the content should make it clear, and then finish the recv() loop and continue to the send() part of the server.

Alright, the solution was pretty simple.
@selalerer was right about the return value of recv() which leads to this working code snippet:

while((c = recv(fd, (char*)&buf[0], bufferSize, 0)))
{
    if(c == -1)
        /* handle error */
    tmp.append(buf.begin(), buf.begin()+c);

    if(c < bufferSize)
        //no more to read, therefore stop reading
        break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM