Search code examples
cprocessminix

Order in which processes will be carried out


I'm fairly new to C, so I apologize if this is a simple question. I'm writing a C program, part of which is below. The goal of the overall program is to copy a file from one location to another (files are passed as arguments, with the final argument being the destination). main(), below, uses fork() to create one child process for each file passed, and I need to print out the file name (just the input argument) along with a message that may include the PID for each copy attempt after all child processes have run.

I can obviously get and use the PID, that's not a problem, but how can I get the right file name/argument that's tied to that process? The method I have in there now is obviously wrong; simply iterating through each argument in order won't be correct. This will be run on Minix 2.0.4, but I don't know if that matters.

int
main(int argc, char *argv[])
{
   int i, pid, rem, status;
   int pids[argc];
   char cfstatus[];

   rem = argc;

   for(i = 1; i < argc; i++) {
      if((pids[i] = fork()) < 0) {
         fprintf(stderr, "Error while forking");
      }
      else if(pids[i] == 0) {
         if(copyfile(argv[i], argv[argc - 1]) == 1)
            exit(4);
         else
            exit(0);
      }
   }

   i = 0;

   while(rem > 1) {
      pid = wait(&status);
      cfstatus = getcfstatus(status, pid);
      printf("%-20s: %s", argv[i], cfstatus);
      rem--;
      i++;
   }
}

Solution

  • As currently written, the child process whose PID is stored in pids[i] will operate on the file named by argv[i]. There's no uncertainty whatsoever about that. i is duplicated along with everything else by the fork operation, and not modified thereafter.

    However, because all the children run in parallel, they may complete in any order. That is, each call to wait might return any of the PIDs in the array (that hasn't already been returned). So what you need to do in your wait loop is map back from the pid value returned by wait, to its index in the pids array, and then you know the right index in argv to print out. For a program like this, a linear search through the array is probably good enough.