pthread_create内存泄漏

时间:2017-12-06 03:45:43

标签: c multithreading sockets tcp memory-leaks

我正在尝试编写一个非常基本的多线程TCP客户端服务器系统,并设法使主要功能工作以及排除除一个以外的任何内存问题。

当服务器关闭的时候,我把它设置为接收和处理一个SIGINT信号,它将关闭listen和connfd以及做一些任意的输出。

问题是valgrind在退出时报告内存泄漏,它说是来自pthread_create并且线程在退出时保持活动状态。当时每个连接用户的泄漏大小为272字节。

Valgrind output

sig处理程序和main的代码如下:

struct timeval t1, t2;
int connfd = 0;
int listenfd = 0;
pthread_t sniffer_thread;

static void SIGhandler(int sig, siginfo_t *siginfo, void *context)
{

    pthread_join(sniffer_thread, NULL);

    shutdown(connfd, SHUT_RDWR);
    shutdown(listenfd, SHUT_RDWR);

gettimeofday(&t2, NULL);

    double totalSeconds = (double) (t2.tv_usec - t1.tv_usec) / 1000000 + (double) (t2.tv_sec - t1.tv_sec) ;

    int seconds = ((int)totalSeconds % 60);
    int minutes = ((int)totalSeconds % 3600) / 60;
    int hours = ((int)totalSeconds % 86400) / 3600;
    int days = ((int)totalSeconds % (86400 * 30)) / 86400;

    printf("\n\nServer shutdown request received");
    printf ("\nTotal server up time = %d days %d hours %d minutes and %d seconds\n\n",days, hours ,minutes , seconds);

    close(connfd);
    close(listenfd);


exit(EXIT_SUCCESS);
}


int main(void)
{

    gettimeofday(&t1, NULL);

struct sigaction act;

memset(&act, '\0', sizeof(act));

// this is a pointer to a function
act.sa_sigaction = &SIGhandler;

// the SA_SIGINFO flag tells sigaction() to use the sa_sigaction field, not sa_handler
act.sa_flags = SA_SIGINFO;

if (sigaction(SIGINT, &act, NULL) == -1) {
perror("sigaction");
exit(EXIT_FAILURE);
}

struct sockaddr_in serv_addr;
struct sockaddr_in client_addr;
socklen_t socksize = sizeof(struct sockaddr_in);
listenfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&serv_addr, '0', sizeof(serv_addr));

serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(50001);

bind(listenfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));

if (listen(listenfd, 10) == -1) {
perror("Failed to listen");
exit(EXIT_FAILURE);
}
// end socket setup

//Accept and incoming connection
puts("Waiting for incoming connections...");
while (1) {
printf("Waiting for a client to connect...\n\n");
connfd =
    accept(listenfd, (struct sockaddr *) &client_addr, &socksize);

printf("\n\nConnection established with: %s\n", inet_ntoa(client_addr.sin_addr));
printf("%s is connected on socket:  %d\n",inet_ntoa(client_addr.sin_addr),connfd);


    // third parameter is a pointer to the thread function, fourth is its actual parameter
if (pthread_create
    (&sniffer_thread, NULL, client_handler,
     (void *) &connfd) < 0) {
    perror("could not create thread");
    exit(EXIT_FAILURE);
}


printf("Handler assigned\n\n");
}

// never reached...
exit(EXIT_SUCCESS);
} // end main()

客户端处理程序代码为:

// thread function - one instance of each for each connected client
void *client_handler(void *socket_desc)
{
    pthread_detach(pthread_self());
//Get the socket descriptor
int connfd = *(int *) socket_desc;

send_conConfirm(connfd);


char choice[8];

do {
            get_menu_choice(connfd,choice);
            switch (*choice) {
            case '1':
                printf("Executing IP/ID return for socket: %d\n",connfd);
            send_studentID(connfd);
        break;
            case '2':
                printf("Executing server time return for socket: %d\n",connfd);
            send_serverTime(connfd);
        break;
            case '3':
                printf("Executing sys info return for socket: %d\n",connfd);
            send_uname(connfd);
        break;
            case '4':
                printf("Executing file list return for socket: %d\n",connfd);
            send_filenames(connfd,choice);
        break;
            case '5':
            send_filenames(connfd,choice);
        break;
            case '6':
                printf("Disconection choice on socket: %d\n",connfd);
        break;
            default:
            printf("Client on socket %d has been disconnected\n", connfd);
                goto jump;
        break;
        }
} while (*choice != '6' );



    jump: //jump for goto statement


shutdown(connfd, SHUT_RDWR);
close(connfd);

printf("Thread %lu exiting\n", (unsigned long) pthread_self());

return 0;
}  // end client_handler()

我尝试了很多不同的方法,包括在完成时分离线程但总是最终导致内存泄漏。即使客户端仅连接并且服务器结束,有时也会发生内存泄漏,有时只有在客户端连接并与服务器交互时才会发生内存泄漏。

1 个答案:

答案 0 :(得分:1)

您需要在while循环结束之前进行连接,而不是在信号捕获函数

我建议您查看本指南的最后几节,他们处理的代码存在一些问题:

  • 连接线程,以便线程不会因为您正在使用而保持打开状态 线程,
  • 你的connfd可以被覆盖(因为它存在于同一个中) 不同线程的内存空间)
  • 将你的while循环调整为 仅在连接打开时运行(将其更改为在 接受的回报)

http://www.binarytides.com/socket-programming-c-linux-tutorial/