accept返回现有连接,导致seg错误

时间:2011-12-22 03:53:14

标签: c multithreading segmentation-fault

我在c中创建一个服务器守护程序,它接受多个同时连接,客户端将向服务器发送数据。我目前将每个客户端连接生成一个新线程。我看到accept()有时(并非总是)会返回现有连接的ID,这显然会导致各种各样的问题,包括分段错误。

我甚至关闭套接字选项SO_REUSEADDR以确保不是这种情况。每当一个客户端进行多次连续调用时,一切都很好(conid在我的代码中增加 - 5,6,7,8,9等等......)。但是,每当有多个客户联系同时连接时,有时conid会重复(一个例子来自一次运行:5,6,7,7,8,9,10,10,10,11,12,12, ...)。

我想知道accept()如何返回现有连接?如果我在多个线程中调用accept(),那将是有意义的,但正如您在下面看到的那样,它只存在于主进程线程中。另一方面,我从来没有遇到select()这个问题,所以也许这是线程问题???在这一点上,我已经尝试了我能想到的一切,但很明显,我只是缺少一些东西

编辑:编辑过的代码,以显示在while循环中mystruct没有被释放,并且(希望)提供更多洞察力。

编辑#2:每个请求,我已经发布了我的示例的完整来源。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <stdarg.h>
#include <time.h>
#include <errno.h>
#include <netdb.h>


//this is my test structure
struct mystruct_ {
    int id; //only id for testing
};
typedef struct mystruct_ mystruct;

//error logging function
void merr(const char *msg, ...) {
    //get the time
    time_t t;
    time(&t);
    //grab this function's arguments
    va_list args;
    char buf[BUFSIZ];
    va_start(args,msg);
    //build the message
    vsprintf(buf,msg,args);
    //output the message
    printf(" ERROR :: %s\n",buf);
    //that's it!
    va_end(args);
}


//this function handles the threads
void *ThreadedFunction(void *arg) {
    //get the passed structure
    mystruct *test = (mystruct *)arg;
    //print conid -- this is where I am seeing the duplicates
    printf("my connection id is %d\n",test->id);
    // do some stuff, like: pull vars out of mystruct
    int nbytes;
    char buf[256];
    while(1) {
        if((nbytes=recv(test->id, buf, sizeof buf, 0)) <= 0) {
            //handle break in connection
            close(test->id);
        } else {
            //for this example, just print out data from client to make my point
            buf[nbytes] = 0;
            printf("%s",buf);
        }
    }
}

//main just sets up the connections and creates threads
int main(int argc, char *argv[])
{
    char *port = "1234";

    //get ready for connection
    struct sockaddr_storage addr;
    socklen_t addrsize = sizeof addr;
    struct addrinfo hints, *res, *ai, *p;
    int sockfd, conid, rv;
    int yes = 1;
    //
    //load up address structs with getaddrinfo():
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;  // use IPv4 or IPv6, whichever
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;     // fill in my IP for me
    if((rv = getaddrinfo(NULL, port, &hints, &ai))!= 0) {
        merr("failed to bind port '%s': %s\n",port,gai_strerror(rv));
        exit(1);
    }
    //
    //bind the port
    for(p=ai; p!=NULL; p=p->ai_next) {
        sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
        if(sockfd<0) continue;
        //setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); //commented for testing
        if(bind(sockfd,p->ai_addr,p->ai_addrlen)<0) { close(sockfd); continue; }
        break;
    }
    //if we don't have p, it means server didn't get bound
    if(p==NULL) { merr("failed to bind port '%s' (reason unknown)",port); exit(2); }
    freeaddrinfo(ai); //all done with this
    //
    // listen to the (now bounded) socket:
    if(listen(sockfd,10)==-1) { merr("listen; errmsg: \"%s\"",strerror(errno)); exit(3); }


    // bind(), listen(), etc... blah blah blah

    mystruct test[1024]; //just for testing
    printf("Ready and Listening...\n");
    while(1) {
        conid = accept(sockfd, (struct sockaddr *)&addr, &addrsize);//get a connection
        test[conid].id = conid;
        pthread_t p;
        pthread_create(&p,NULL,ThreadedFunction,&test[conid]); //create new thread
    }
}

2 个答案:

答案 0 :(得分:1)

这是破碎的:

while(1) {
    conid = accept(sockfd, (struct sockaddr *)&addr, &addrsize);//get a connection
    test[conid].id = conid;
    pthread_t p;
    pthread_create(&p,NULL,ThreadedFunction,&test[conid]); //create new thread
}

pthread_t p;在堆栈上声明一个pthread_create将填写的不透明句柄。该句柄的生命周期必须持续到您致电pthread_joinpthread_detach

在这种情况下,pthread_t的存储可能正在被重用,搞乱了将参数传递给线程函数。至少,这是我的猜测。

尝试在pthread_detach后调用pthread_create

答案 1 :(得分:1)

accept返回一个我可以重用的文件描述符。由于您的ThreadedFunction在使用文件描述符时永远不会终止,因此您将获得竞争条件。所以在close语句放置return;

之后