0

I write a simple kernel module which include the following ksocket connection accept codes:

.....(some ksocket initiation)

while( on_service )
{
    sockfd_c = kaccept(sockfd_s, (struct sockaddr *)&addr_cli, &addr_len);
    kclose(sockfd_c);
}

And write a simple client to connect to this socket server. From console, I found the memory usage is increasing by "free" command when I continuously run the client connection.

The functions of kaccept() and kclose() are as follows.

int kclose(ksocket_t sockfd)                                                                                                                                                                                     
{
    struct socket *sk;
    int ret;

    sk = (struct socket *)sockfd;
    ret = sk->ops->release(sk);

    if (sk)
    {   
        sock_release(sk);
    }   

    return ret;
}

ksocket_t kaccept(ksocket_t socket, struct sockaddr *address, int *address_len)
{
    struct socket *sk;
    struct socket *new_sk = NULL;
    int ret;

    sk = (struct socket *)socket;

    sxg_debug("family = %d, type = %d, protocol = %d\n",
                sk->sk->sk_family, sk->type, sk->sk->sk_protocol);
    //new_sk = sock_alloc();
    //sock_alloc() is not exported, so i use sock_create() instead
    ret = sock_create(sk->sk->sk_family, sk->type, sk->sk->sk_protocol, &new_sk);
    if (ret < 0)
        return NULL;
    if (!new_sk)
        return NULL;

    new_sk->type = sk->type;
    new_sk->ops = sk->ops;

    ret = sk->ops->accept(sk, new_sk, 0 /*sk->file->f_flags*/);
    if (ret < 0)
        goto error_kaccept;

    if (address)
    {
        ret = new_sk->ops->getname(new_sk, address, address_len, 2);
        if (ret < 0)
            goto error_kaccept;
    }

    return new_sk;

error_kaccept:
    sock_release(new_sk);
    return NULL;
}

Does there anybody know why/how the memory leak?

4

2 回答 2

0

Use valgrind to find memory leaks

as

valgrind ./your_program
于 2013-09-04T07:32:48.130 回答
0

My kernel version is 3.2 and I am trying to write a kernel socket server. After several days' fighting, I have the following finding.

I user sock_create() to create a socket server and then listen and accept connection by

sockfd_srv = sock_create(...)
...
while(1) {
    sockfd_srv->ops->listen();
    sockfd_cli = sock_create(...);
    sockfd_srv->ops->accept(..., &sockfd_cli);
    ....(do something)
    sock_release(sockfd_cli);
}

The above program will cause the memory leak even I DO release clients' socket by sock_release(). Finally, the system will be out of memory.

I change it as follows where I use sock_create_lite() instead of sock_create().

sockfd_srv = sock_create(...)
...
while(1) {
    sockfd_srv->ops->listen();
    sockfd_cli = sock_create_lite(...);
    sockfd_srv->ops->accept(..., &sockfd_cli);
    ....(do something)
    sock_release(sockfd_cli);
}

Then the memory leak problem is gone.

于 2013-09-05T13:27:01.533 回答