RobStl10
asked on
Shell Background Processing in C
Hey Experts!
I am currently having issues running a background process in my shell that I have created. Whenever I invoke the background process, by typing an '&' symbol after the commands, the program runs the process in the background, then exits my program. Can anyone explain why this is happening?
Here is my function that handles new processes:
I do not think that I am implementing this idea correctly.. Any help would be greatly appreciated!!! :D ~Rob
I am currently having issues running a background process in my shell that I have created. Whenever I invoke the background process, by typing an '&' symbol after the commands, the program runs the process in the background, then exits my program. Can anyone explain why this is happening?
Here is my function that handles new processes:
void initProcess()
{
int status = 0;
int pid = fork();
if (pid == 0) {
// child process
if(background) {
fclose(stdin); // close child's stdin
fopen("/dev/null", "r"); // open a new stdin that is always empty
}
execvp(*commandArguments,commandArguments);
// If an error occurs, print error and exit
fprintf (stderr, "unknown command: %s\n", commandArguments[0]);
exit(0);
} else {
// parent process, waiting on child process
//waitpid(pid, &status, 0); //old code..
if (background) {
printf("starting background job %d\n", pid);
childpids [nChildren] = pid;
nChildren++;
execvp(*commandArguments,commandArguments);
} else {
waitpid(pid, &status, 0);
}
if (status != 0) //process exits if error occurs
fprintf (stderr, "error: %s exited with status code %d\n", commandArguments[0], status);
}
}
I do not think that I am implementing this idea correctly.. Any help would be greatly appreciated!!! :D ~Rob
Have you tried running it without the trailing '&' to see what happens?
ASKER
Well, if I don't use the '&' symbol, it runs fine as a normal process. My issue only occurs when I use the '&' symbol. It prints out "Starting background process X", where X is the pid of the process. But then exits my shell.
Should I include more code so that you are able to see the entire shell process?
Should I include more code so that you are able to see the entire shell process?
Actually, if you are running in the background, then I'm not sure that you see any output - in the background, the task runs disconnected from a terminal.
Try closing stdout and then opening it to a file (similarly to what you did with stdin except not /def/null ) and see if you get some output.
Try closing stdout and then opening it to a file (similarly to what you did with stdin except not /def/null ) and see if you get some output.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Excellent! Glad you got it working; and thanks for the updated code. It looks like properly setting the background variable was a key element...