linux socket服务器突然停止

时间:2014-03-31 22:37:44

标签: c++ c linux sockets

我正在尝试编写一个基于套接字的客户端/服务器程序,它可以连续地交换消息。我遇到了一个问题。从客户端收到1或2条消息后服务器程序突然停止,并且不再继续。你能告诉我可能出现的问题吗?套接字代码的内部大致基于beej's guide中给出的流套接字服务器/客户端。

我的服务器代码:

void sigchld_handler(int s)
{
 //       while(waitpid(-1, NULL, WNOHANG) > 0);
          wait(NULL);
} 

int main()
{
    int numbytes;
    u32 size = 0;
    s8 buf[1024] = "Hello World";
    s8 recvbuff[1024];
    cpl_Socket s1("127.0.0.1","3490",E_ServerSocket);
    s1.registerSocket();
    s1.listenOnPort();
        sa.sa_handler = sigchld_handler; // reap all dead processes
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    if (sigaction(SIGCHLD, &sa, NULL) == -1) 
    {
        perror("sigaction");
        exit(1);
    }
    cpl_Socket newFd;
        struct sigaction sa;
    while(1)
    {
        if ( newFd.acceptConn(s1.getSocketFd()) != e_success)
        {
            LOG(warn,"Accept Error");
            continue;
        }
        if (!fork())
        {
            close(s1.getSocketFd());
            size = (u32)strlen(buf);
            numbytes = newFd.SocketTx(buf,size);
            if (numbytes < 0)
            {
                perror("Write");
                LOG(fatal,"Write to Socket Failed\n");
            }
            LOG(info, "Server sent[%s], bytes [%d]\n",buf,numbytes);
            while (1)
            {
                                cout <<"Child here\n";
                numbytes = newFd.SocketRx(recvbuff,sizeof(recvbuff));
                LOG(info, "Server received[%s], bytes[%d]\n", buf,numbytes);
                cout <<"Enter string to send to client:";
                cin >> recvbuff;
                newFd.SocketTx(recvbuff,strlen(recvbuff));
            }
        }
                cout <<"Back to parent\n";
        close(newFd.getSocketFd());
    }
        cout <<"Back to parent again\n";
        wait(NULL);
    close(s1.getSocketFd());
    return(0);
}

我的服务器输出示例如下:

    CommonUtils$ [[DEBUG]][comm_ipc.cpp:acceptConn():149]->
    New connection from 127.0.0.1 received on socket 4

    Server sent[Hello World], bytes [11]
    Server received[hi], bytes[1048576]
    Enter string to send to client:k
    k: command not found

    [1]+  Stopped                 ./server

    [1]+  Stopped                 ./server

0 个答案:

没有答案