子进程内存泄漏。如何处理子进程中的内存

问题描述 投票:0回答:1

我正在编写一个终端并使用以下函数来执行命令:

void    execute_input(t_list *node, char **envp)
{
    int     pid1;
    int     status;

    if (ft_lstsize(node) > 1)
        command_chain(node);
    else if (is_builtin(node))
        execute_builtin(node);
    else
    {
        get_data()->executing_cmd = 1;
        pid1 = fork();
        if (pid1 == 0)
        {
            if (!access(node->token[0], X_OK))
                node->path = node->token[0];
            execve(node->path, node->token, envp);
            exit(errno);
        }
        waitpid(pid1, &status, 0);
        if (WIFEXITED(status))
            get_data()->exit = WEXITSTATUS(status);
        get_data()->executing_cmd = 0;
    }
}

node->path
node->token
在父级中动态分配。

当我的execve因为无法执行程序而返回-1时,我会出现一些我无法解决的奇怪的内存泄漏。

我不知道如何处理这种情况。我尝试在 execve 之后释放子进程中的内存,但这将导致无效的释放。

子进程应该如何处理父进程分配的内存?

c fork execve
1个回答
1
投票

如果

execve
失败,您将立即退出子进程 [从技术上讲,您应该使用
_exit
而不是
exit
来执行此操作,但现在不用担心]。

当您退出子进程时,操作系统会释放分配给它的 all 资源,包括

malloc
分配的所有资源。

因此,没有必要在子进程中显式释放任何东西。

© www.soinside.com 2019 - 2024. All rights reserved.