user1563544
user1563544

Reputation: 377

How do I wait for child processes to end

The title speaks for itself. Here's the function:

void fork_and_chain(int * pipein, int * pipeout, Command *cmd, int size)
{
    auto pid = fork();
    int status;

    if(!pid)
    {
        if(pipein) {
            dup2(pipein[0], 0);
            close(pipein[0]);
            close(pipein[1]);
        } else if (cmd->redirectin) {
            int fin = open(cmd->filename.c_str(), O_RDONLY);
            dup2(fin, 0);
            close(fin);
        }

        if(pipeout) {
            dup2(pipeout[1], 1);
            close(pipeout[0]);
            close(pipeout[1]);
        } else if (cmd->redirectout) {
            int fout = open(cmd->filename.c_str(), O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR);
            dup2(fout, 1);
            close(fout);
        }

        if (execvp(cmd->args_char[0], cmd->args_char.data()) < 0) {
            std::cerr << "Command not Found" << std::endl;
        }
    } else if (pid < 0) {
        std::cerr << "Fork failed." << std::endl;
        exit(1);
    } else {
        // waiting for child process to finish
    }
}

Whatever I put there I get an infinite loop (I'm making a shell). I either get the "cmd" prompt infinitely or nothing at all. The chaining code continues running and I don't know hot to terminate it.

Upvotes: 1

Views: 91

Answers (1)

brandx
brandx

Reputation: 1053

I think you're looking for waitpid(). In your comment section add:

int status = 0;
waitpid(pid, &status, 0);
std::cerr << "child finished with status: " << status << std::endl;

Upvotes: 1

Related Questions