0

I try to get the exit code from a child of a child process in the parent process. If the process goes in the while loop to fork again i don't get the exit code. I tried some options for waitpid like WNOHANG but then the program hangs. Maybe what i wan't is not possible because it's some like a zombie child?

This is my code.

void    parrent_process(t_token *token, t_info *info)
{
    pid_t   pid;
    int     wstatus;

    pid = fork();
    if (pid == -1)
        return (print_error_msg(FORK_FAIL, NULL, NULL));
    if (pid == 0)
    {
        child_process(token);
    }
    if (info->in)
        close(info->in);
    waitpid(pid, &wstatus, 0);
    if (WIFEXITED(wstatus))
        info->exit_code = WEXITSTATUS(wstatus);
}

void    child_process(t_token *token)
{
    t_token *cmd_token;
    pid_t       pid;

    pid = 0;
    cmd_token = token;
    while (token->next && ((token->next)->type == GREAT))
    {
        pid = fork();
        if (pid == -1)
            return (print_error_msg(FORK_FAIL, NULL, NULL));
        if (pid == 0)
        {
            redirect_output(token);
            break;
        }
        token = token->next->next;
    }
    if (execve(cmd_token->path, cmd_token->args, cmd_token->envp) == -1)
    {
        print_error_msg(CMD_NOT_FOUND, "minishell", cmd_token->args[0]);
        exit(127);
    }
}
  • You haven't provided a full example but the normal idiom is a strict branch at the point of fork. This `if` statement runs on `if (pid == 0) { child_process(token); }' where the normal idiom would be an `else` or `return`. If the parent is closing `info->in` before the child processes finish that could cause it to hang. – Persixty Jul 29 '22 at 11:50
  • 1
    In POSIX-like systems, the answer is No. Linux has a facility whereby a process can become responsible for its descendants rather like the init process normally does. If the child process waits for the grandchild, the parent still won't see the grandchild’s status even so. Working from under-caffeinated memory, it's a feature of `prctl()` — process control. – Jonathan Leffler Jul 29 '22 at 12:44

1 Answers1

0

In most POSIX-like systems, the answer is "No — a process can only wait on its own children, those it created directly with fork()1".

However, on Linux, there is the prctl(2) system call. The option PR_SET_CHILD_SUBREAPER allows a process to wait for more distant descendants (grandchildren, great-grandchildren, …) too. However, if the direct parent of a process waits for it, the ancestral process will not get the exit status information.

1 Or posix_spawn()

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278