Operating Systems – How to Implement bg, &, and fg Commands in a Custom Unix Shell Program

operating systemssystems-programming

I am extending the functionality of a custom unix shell which I wrote as part of my lab assignment. It currently supports all commands through execvp calls, in-built commands like pwd, cd, history, echo and export, and also redirection and pipes. Now I wanted to add support for running a command in background e.g. $ls -la& I also want to implement bg and fg job control commands.

I know this can be achieved if I execute the command by forking a new child process and not waiting for it in the parent process. But how do I again bring this command to foreground using fg? I have the idea of entering each background command in a list assigning each of them a serial number. But I don't know how do I make the processes execute in the background, then bring them back to foreground. I guess wait() and waitpid() system calls would come handy but I am not that comfortable with them. I tried reading the man pages but still am in the dark. Can someone please explain in a layman's language how to achieve this in UNIX system programming? And does it have something to do with SIGCONT and SIGSTP signals?

Best Answer

Suspending a command (CTRL-Z) works by sending a SIGTSTP to the child process. The shell is then free to interact with the user via stdin/stdout.

Resuming is accomplished by sending SIGCONT to the child process and then continuing to wait for it to finish.

Backgrounding a process is accomplished by sending SIGCONT but not waiting for it to finish. In this case, both the shell and the child process can interact with stdout/stderr, but stdin is typically intercepted by the shell.

Starting a process in the background is accomplished by doing a fork/exec, but not blocking until the child process exists.

Typically (as in always) a shell will also handle SIGCHLD, which is the way the OS notifies the parent process that a child processes has finished so that the parent can collect the exit code. Otherwise you end up with "zombie" processes; ones which aren't running but which haven't yet been collected by a parent.

Related Topic