Run a list of executables

Asked

Viewed 94 times

3

I am trying to implement a program that runs concurrently a list of specified executables as command line arguments, considering 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 perform :

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’ve 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?

  • I think the best way to make a system with competition is to use threads instead of fork, the fork creates a new process, and variables can only be used in a process (except if it is a shared variable)

  • That’s what I thought @Brumazzid.B. but I can only use Fork and its execs.

1 answer

1


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

This second fork() never executes.
After the execvp() the current program is replaced by another and the fork() ceases to "exist".


First you do the fork(). Then, just in the son, you do the exec(). So you get two active processes: the father running the original program and the son 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 a Wikipedia article (in English) on the Fork-exec.

  • Very well noted @pmg . So if using any exec it does not make Fork process? How do I make exec run according to Fork?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.