0

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 ?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

8 Comments

Can you give me a simple example of how to use fork, and then I Don't need the for loop to circle through my array then if I used the fork ??
@pro: i just added a link to man wait (although you should have that on your machine) which includes a complete example. Of course, you still need the for loop.
Ok I edited my code, I am trying to follow this example provided here cs.ecu.edu/karl/4630/sum01/example1.html but the thing is , if we are in the parent process how would we wait until the child is done ! should I just use waitpid() which by default wait for the chidlren to terminate ??
@pro: please don't edit your questions after they have been answered, particularly in ways which make the answer inappropriate. If you want to ask a different question, ask a different question.
I think my code, is good now because wait(&status) puts the parent to sleep until the child is done right ??
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.