Home > database >  Fork() and execv() not running in parallel, why?
Fork() and execv() not running in parallel, why?

Time:03-30

I'm trying to run a series of commands through execv() and forking a new process in C to run each one, and yet for some reason they aren't running in parallel. The following code is run for each process, with "full" being the filepath and "args" being the arguments. I know that the execv() part isn't the issue, it has to do with the way I'm forking and waiting.

            int status;
            pid_t pid = fork();

            if (pid == 0) {
                execv(full, args);
                //perror("execv");
            } else if (pid < 0) {
                printf("%s\n", "Failed to fork");
                status = -1;
            } else {
                if (waitpid(pid, &status, 0) != pid) {
                    status = -1;
                    return status;
                }
                
            }

When running this code, the forked commands simply run one after the other. I don't know how this could be happening.

CodePudding user response:

If you don't want to wait for each child process, don't call waitpid immediately; as written, you fork a child, then immediately stop all processing in the parent until the child process exits, preventing you from forking any further children. If you want to launch multiple children without leaving zombie processes lying around (and possibly monitoring them all at some point to figure out their exit status), you can do one of:

  1. Store off the pids from each fork in an array, and call waitpid on them one by one after you've launched all the processes you need to launch
  2. Store a count of successfully launched child processes and call wait that many times to wait on them in whatever order they complete.
  3. Ignore the SIGCHLD from the child processes entirely, for when you don't care when they exit, don't need to know their status, etc.
  • Related