1
votes

Greeting !!

I use unpv13e library in linux developed as socket server , and listen a port which will accept 3 socket clients (at most) , each client would has its own thread ....

While these 3 clients send very very quick , the recv function of socket server will receive said half of string came from client1 , half of another came from client2 , it is odd because I think these 3 socket clients would be run in different thread , also different socket id , so I am curious why it happened ? let me explain in the following codes :

listenfd = Tcp_listen(ipaddr,portno,&addrlen);
cliaddr = Malloc(addrlen);
Signal(SIGINT, sig_int);
for ( ; ; ) {
    clilen = addrlen;
    connfd = Accept(listenfd, cliaddr, &clilen);
    err_msg("id [%05d] conned from %s",connfd,Sock_ntop(cliaddr, clilen));
    Pthread_create(&tid, NULL, &doit, (void *) connfd);
}


void * doit(void *arg)
{
    void web_child(int);
    Pthread_detach(pthread_self());
    web_child((int) arg);
    Close((int) arg);
    printf("thread [%05d] dead...\n",(int) arg);
    return(NULL);
}


void web_child(int sockfd)
{
    int        connfd;
    ssize_t    nread;
    char       line[1024];

    for ( ; ; )
    {
        line[0]=0x00 ;
        if ( (nread = Readline(sockfd, line, 1024)) == 0)
            break;         /* connection closed by other end */
        line[nread-2]=0x00 ;
        if(strncmp(line,"101",3)==0)
            Do101(line) ;
        if(strncmp(line,"201",3)==0)
            Do201(line) ;
        if(strncmp(line,"301",3)==0)
            Do301(line) ;
    }
}

Readline function in unpv13e library call recv , and check one char at a time until it is a '\n' and return , the nread usually 315 bytes or so , and I do not have send in this socket server !! In my opinion , web_child function is run as thread , with different socketfd , and line is local var , so it is no way that 3 different client will effect each other, socket client1 will always send string start with "101" , and client2 always send "201", client3 send "301" ....

But somestimes I'll see a string in Do101(line) , which the firat half of it is "101" , and second half of it came from client2 , they just effect each other ... if these 3 clients send very very frequently , it might happened ... not very often , but it just happened !!

What kind of bug I've in the code ? recv from different socketid in different thread will effect each other ?

Any suggestion are welcome !! Thanks !!

2

2 Answers

2
votes

Is this the library you're using? https://github.com/k84d/unpv13e/

The readline functions don't appear to be threadsafe. They use a static buffer and nothing to guard against concurrent access.

2
votes

If Readline() receives only 1 byte, this line fails:

line[nread-2]=0x00 ;

You might try changing it into:

line[nread-1]=0x00 ;