Pro
Pro

Reputation: 173

using execvp to execute commands that I have in an array

I have a commands array and I want to execute each command in this array but I couldn't seem to get it working so I have

childPid = fork();


for(int i =0;i < numOfCommands;i++)
{
    if(childPid == 0)
    {
        execvp(commands[i], argv);
        perror("exec failure");
            exit(1);
    }
    else 
    {
        wait(&child_status);
    }


}

What this does, is that it only executes the 1st command in my array but doesn't proceed any further, how would I continue ?

And what if i want the order for the commands to executed randomly and the results be intermixed so do I have to use fork then ?

Upvotes: 0

Views: 285

Answers (1)

rici
rici

Reputation: 241861

You need to use fork in any case, if you want to execute more than one program. From man exec: (emphasis added)

The exec() family of functions replaces the current process image with a new process image.

The exec() functions return only if an error has occurred.

By using fork, you create a new process with the same image, and you can replace the image in the child process by calling exec without affecting the parent process, which is then free to fork and exec as many times as it wants to.

Don't forget to wait for the child processes to terminate. Otherwise, when they die they will become zombies. There is a complete example in the wait manpage, linked above.

Upvotes: 2

Related Questions