Calling Fork for a subprocess

85 views Asked by At

I am implementing a shell in C but when Im using fork() it creates too child process. Here is my code :

int exec_simple_command(struct ast_node_simple_command *node)
{
    if (node == NULL)
        return 1;


    char **args = node->words;
    if (args == NULL)
        return 1;

    pid_t pid = fork();
    int status;

    /* Error handling */
    if (pid < 0)
        return -1;

    if (pid == 0) /* Child Process */
    {
        return exec_builtin(args);
    }
    else
    {
        if (waitpid(pid, &status, 0) < 0)
        {
            return 2;
        }

        return 0;

    }
}

i have file with simple command to test my shell :

echo 1;
echo 2;
echo 3;
echo 4;

And here is the output i get :

1
2
3
4
4
3
4
4
2
3
4
4
3
4
4

every time I execute a new builtin it duplicates the number of child. I just want to execute on child, wait before the child process terminated and then continue the rest of the program. Thanks for your help.

0

There are 0 answers