简体   繁体   中英

Implementation of fork exec wait

So I am trying to understand the implementation of fork exec and wait. The program should execute a given program multiple times with different command line arguments each time.

The first command line argument is the name of the program to repeatedly execute.

For each other command line argument run the program with that argument as its only argument. Wait for each child to finish before running the next child process.

So ideally if I run something like ./main echo one two three.

It should give me something like:

one 
two 
three

But for some reason, I only get the first argument. What am I doing wrong? Thank you

int main(int argc, char** argv){
 if (argc <2) {
    return 1;
}

for (int i = 2; i <argc; i++){
  if(!fork()) {
    argv[0] = "echo";
    argv[1] = argv[i];
    argv[2] = 0;
    
    execvp("echo",&argv[0]);

    wait(0);
   }
 }
}

There are multiple issues in your code.

Here the most relevant:

  1. you're overwriting the content of argv[], so after the first loop cycle you loose the input parameters. That's why you only get the first argument

  2. the execvp() function doesn't return unless it fails, so you should handle a possibile error after execvp()

  3. the wait() function is in the wrong place; it should be outside the child creation loop and inside another loop that checks the result for every child

  4. the wait() function should allow you to read the exit status value and understand what happened to the corresponding child, like in the form:

     int status, pid; pid = wait(&status);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM