Run a list of executables

Question:

I'm trying to implement a program that concurrently executes a list of executables specified as command line arguments, considering the executables without any arguments of their own. The program must wait for the end of the execution of all processes created by it.

I can only use these functions to execute:

int execl(const char*path, const char*arg0, ..., NULL);
int execlp(const char*file, const char*arg0, ..., NULL);
int execv(const char*path, char*const argv[]);
int execvp(const char*file, char*const argv[]);

This is what I created so far :

void main (int args , char **s) {

   int  i , x , status;

   if (args >= 2) {

    x = fork ();

    for ( i = 1 ; i < args ; i++) {

         if (x == 0) {
            execvp (s[i],&s[i]);
            x = fork();
         }
         else
         {
            wait (&status);
            _exit(i);
         }
      }
  }
   _exit(0);
}

But the program only executes the first argument of main . How can I change the code to do what I want?

Answer:

         if (x == 0) {
            execvp (s[i],&s[i]);
            x = fork();          // <== nunca executa
         }

This second fork() never executes.
After execvp() the current program is replaced by another one and fork() longer "exists".


First you fork() . Then, just on the child, you do exec() . That way you have two active processes: the parent running the original program and the child running the exec program.

// basicamente (MUITO BASICAMENTE) é isto
if (fork() == 0) {
    exec();     // o filho passa a executar outro programa
}               // o pai continua a executar este programa

There's an article on Wikipedia about fork-exec .

Scroll to Top