c - fork() function will never return 0 -
i trying run fork function in c in child section of code, trying execute command using exacvp, before execution trying printf function never executes. ran in debug , have noticed pid never assigned 0. did try simple fork example on separate project , worked smoothly. have idea why child section never executes?
int startprocesses(int background) { int = 0; while(*(linearray+i) != null) { int pid; int status; char *processname; pid = fork(); if (pid == 0) { printf("i 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 flushed on program's exit, execvp
directly replaces process image, bypassing flush-at-exit mechanism , leaving i child
message in memory never sent screen. add explicit fflush(stdout)
before execvp
, or end string \n
automatically flushed when running on tty.
note execvp
never exits, , if does, because has failed execute new process. @ point, only thing child can report error , call _exit(127)
(or similar exit status). if child continues, incorrectly configured command name cause execute rest of parent's loop in parallel parent. process continue other descendants, creating fork bomb can grind system halt.