Link to home
Start Free TrialLog in
Avatar of RobStl10
RobStl10Flag for United States of America

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:
 
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);
    }
}

Open in new window


I do not think that I am implementing this idea correctly.. Any help would be greatly appreciated!!! :D   ~Rob
Avatar of JESii
JESii
Flag of United States of America image

Have you tried running it without the trailing '&' to see what happens?
Avatar of RobStl10

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?
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.
ASKER CERTIFIED SOLUTION
Avatar of RobStl10
RobStl10
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Excellent! Glad you got it working; and thanks for the updated code.  It looks like properly setting the background variable was a key element...