Home:ALL Converter>C program that tells the user which child process finished first

C program that tells the user which child process finished first

Ask Time:2017-12-06T07:57:21         Author:DrJessop

Json Formatter

I am working on an assignment that involves using fork. The program runs two separate programs simultaneously and tells the user which one finished first. If a child finishes, the other child still running should be killed immediately. My code so far is this...

int main(int argc, char **argv) {

  if (argc != 2) {
    perror("Invalid number of arguments!");
    exit(1);
  }
  pid_t pid;
  pid_t wpid;
  int status = 0;

  for (int i = 0; i < 2; i++) {
    if ((pid = fork()) == 0) {
      execv("/bin/sh", argv[i+1]);
    } 
  }
  while ((wpid = wait(&status)) > 0);
  printf("%s finished first!", <Insert winning program here>);
  return 0;
}

From my understanding, this runs the programs and will not let the parent process continue until the child processes have finished. Now I'm wondering how I can terminate another child and return the winning process.

Author:DrJessop,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/47664647/c-program-that-tells-the-user-which-child-process-finished-first
yy