简体   繁体   中英

fork() function will never return 0

I am currently trying to run a fork function in C where in the child section of the code, I am trying to execute a command using exacvp, but before the execution I am trying a printf function which never executes. I ran this in debug and I have noticed that the pid is never assigned 0. I did try a simple fork example on a separate project and it worked smoothly. Does anyone have an idea why the child section never executes?

int startProcesses(int background) {
int i = 0;

while(*(lineArray+i) != NULL) {
    int pid;
    int status;
    char *processName;

    pid = fork();

    if (pid == 0) {

        printf("I am child");
        // Child Process
        processName = strtok(lineArray[i], " ");
        execvp(processName, lineArray[i]);
        i++;
        continue;

    } else if (!background) {

        // Parent Process
        waitpid(pid, &status, 0);
        i++;
        if(WEXITSTATUS(status)) {
            printf(CANNOT_RUN_ERROR);
            return 1;
        }
    } else {
        i++;
        continue;
    }
}
return 0;

}

stdio files are flushed on program's exit, but execvp directly replaces the process with another image, bypassing the flush-at-exit mechanism and leaving the I am child message in memory never to be sent to the screen. Add an explicit fflush(stdout) before execvp , or end your string with \\n so that it is automatically flushed when running on a TTY.

Note that execvp never exits, and if it does, it is because it has failed to execute the new process. At that point, the only thing the child can do is to report an error and call _exit(127) (or similar exit status). If the child continues, an incorrectly configured command name will cause it to execute the rest of the parent's loop in parallel with the parent. This process will continue for other descendants, effectively creating a fork bomb that can grind your system to a halt.

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