I have a problem where I am trying to run multiple commands through execvp(). To do this, I have a while loop doing through each command, parsing it, then calling a function to use fork + exec.
The issue is, I will run fork + exec, and while I wait for the exec to go through, the parent runs and continues on to the second loop, ie. the second command. But what happens, from my understanding, is the child process from the previous loop takes over and all of a sudden, the child process is the current process.
How do you run a process in the child process, but maintain control in the parent? All the examples I've seen on SO have been for parent processes what wait for the child process to terminate before continuing, but I don't have a choice in this assignment - I'm supposed to keep the child processes running and check later to see if they're still running.
Here's some pseudocode of my thought process:
funct forkprocess() {
//call fork
//call execvp within child process, let process run and return control to parent
//if execvp failed, kill child process
//return child pid
}
int main() {
while(not end of file containing list of commands) :
//parse command for execvp call
//call forkprocess() to run process
//if childpid is returned, report it and store pid
//else, report failure
}
}
My output has been close to the following:
\\parent PID is printed
\\any code outside the if-else ladder for fork is printed
\\it jumps back to main and prints any statements there
[jumps to next iteration in loop, ie. the next command]
\\child PID is printed
\\parent PID is printed
\\any code outside the if-else ladder for fork is printed
\\it jumps back to main and prints any statements there
\\child PID is printed