[英]Memory leak by using ksocket
I write a simple kernel module which include the following ksocket connection accept codes: 我编写了一个简单的内核模块,其中包含以下ksocket连接接受代码:
.....(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.
从控制台,我发现在连续运行客户端连接时,“ free”命令会增加内存使用量。
The functions of kaccept() and kclose() are as follows. kaccept()和kclose()的功能如下。
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? 有谁知道为什么/如何内存泄漏?
Use valgrind
to find memory leaks 使用
valgrind
查找内存泄漏
as 如
valgrind ./your_program
My kernel version is 3.2 and I am trying to write a kernel socket server. 我的内核版本是3.2,我正在尝试编写一个内核套接字服务器。 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 我使用sock_create()创建套接字服务器,然后通过侦听并接受连接
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(). 即使我通过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(). 我在使用sock_create_lite()而不是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. 然后内存泄漏问题消失了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.