分叉和内存分配
我对算法的并行实现进行编程,该算法使用非线程安全操作。因此我使用 fork() 和 POSIX-Shared Memory,效果很好。现在问题来了。当子进程退出时,父进程动态分配的内存会发生什么? 代码看起来像这样
int compute(....) {
// prepare shared memory
pid_t child = fork();
if ( child == 0 ) {
// process the child code
int *workspace = malloc(worksize*sizeof(int));
// copy the result to Shared memory
free(workspace);
exit(0);
}
// do parents work
wait(&status);
// retrieve results from shared memory
return 0;
}
问题是我不知道从哪里调用compute以及分配了哪些内存。我唯一希望我可以授予的是父级分配的内存仅在子级中只读使用。子进程分配的动态分配内存由子进程释放。 这是否会导致内存泄漏? Valgrind 说是的,但我没有办法避免这种情况。不幸的是,跟踪所有内存分配是不可能的。
I programming on a parallel implementation of an algorithm, which uses non thread-safe operations. Therefore I use fork() and POSIX-Shared Memory, which works fine. Now the questions. What happens with the dynamicaly allocated memory of the parent, when the child exits?
The code looks like this
int compute(....) {
// prepare shared memory
pid_t child = fork();
if ( child == 0 ) {
// process the child code
int *workspace = malloc(worksize*sizeof(int));
// copy the result to Shared memory
free(workspace);
exit(0);
}
// do parents work
wait(&status);
// retrieve results from shared memory
return 0;
}
The problem is that I do not know from where compute is called and which memory is allocated their. The only thing I hope I can grantee is the memory that is allocated by the parent is only used read only in the child. Dynammically allocated memory which is alloced by the child is freed by the child.
Does this cause a memory leak or not? Valgrind says yes and I dont have an idea to avoid this. Tracking all memory allocations is unfortunately not possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果代码看起来与所示完全相同,则不会产生内存泄漏。正如你所说,孩子在退出之前释放了所有内存。 valgrind 在计算分叉进程时可能会遇到一些问题。
If the code looks exactly as shown, no memory leak is produced. As you say, the child frees all its memory before exit. valgrind may have some problems accounting
fork
ed processes.