Unix Domain Socket(C ++) - 客户端崩溃服务器守护程序

时间:2015-04-24 07:00:56

标签: c++ linux sockets unix


我有一个很大的问题 我最近开始使用守护进程和套接字编程。我当前的设置包括一个守护进程,它创建一个套接字和一个写入消息并读取已处理答案的客户端 那么,阅读答案。

守护进程守护自身,创建套接字甚至处理消息(我可以通过我做的日志条目进行验证)但是一旦我尝试将答案发送到客户端,守护进程就会被阻止;客户端永远不会收到答案,如果我ctrl-c客户端,守护程序也会关闭 这对我来说是完全奇怪的行为,我无法解释发生了什么,这就是为什么我会问你任何提示。

摘要:
  - 套接字类型为AF_UNIX,因此本地且不涉及网络   - 守护程序成功接收消息,但无法写回   - 客户端无法读取(因为服务器的send()正在阻止)和 如果我ctrl-c客户端守护进程也退出(但该信号没有被发送到守护进程)

下面是我的代码,被剥离到有趣且无法工作的部分 非常感谢提示,帮助和建议!

更新

还添加了客户端代码!

int main()
{
    //those two work just fine
    createSocket();
    daemonize();

    //declare some variables needed in the big loop
    FILE *client_fd;
    int fd;
    socklen_t len;
    string tmp;
    char *buf = new char[1024];
    while(1)
    {
        struct sockaddr_un saun;
        len = sizeof(saun);

        //receive an fd for the incoming connection
        if((fd = accept(m_socket, (sockaddr*)&saun, &len)) < 0)
        {
            writeLog("Accepting connection failed!");
            continue;
        }
        //i wanted to use fgets, therefore obtain a FILE object here
        client_fd = fdopen(fd, "r");
        if(client_fd == NULL)
        {
            writeLog("fdopen() failed!");
            continue;
        }
        while(fgets(buf, bufferSize, client_fd) != NULL)
        {
            //message read succeeds (verified)
            writeLog(buf);
            tmp = evaluateMsg(buf);

            //tmp is not empty (verified)
            writeLog(tmp);

            //send seems to block, nothing happens from now on
            //I don't even get in one of the if-else branches
            if(send(fd, (tmp + "\n").c_str(), tmp.size() + 1, 0) < 0)
            {
                writeLog("Could not write message back!");
                continue;
            }
            else
                writeLog("bytes written!");
        }
        close(fd);
    }
}

以下是客户端代码:

int main()
{
    int sockfd;
    sockaddr_un addr;

    sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
    addr.sun_family = AF_UNIX;
    strcpy(addr.sun_path, SOCKET_PATH);

    //the connection is successfull
    if(connect(sockfd, (sockaddr*)&addr, sizeof(addr)) < 0)
    {
        cerr<<"Connection failed!"<<endl;
        exit(1);
    }
    //message is written successfully
    write(sockfd, "hello", 5);
    char *buf = new char[1024];

    //same as for the server, I wanted to use fgets
    //therefore need to obtain a FILE object
    FILE *fd = fdopen(sockfd, "r");
    fgets(buf, 1024, fd);
    cout<<buf<<endl;

    close(sockfd);
}

1 个答案:

答案 0 :(得分:0)

好吧,我自己找到了解决方案。

问题是对fgets()的(方便)调用;我不得不使用read(),现在一切都像魅力一样 我不确定为什么read()是强制性的,但我认为它与缓冲区有关,缓冲区只要读取就清空了...
但这只是我的假设!