Build a simple Unix shell in C with job control supporting Ctrl+Z, fg, and bg commands. Manage process groups with setpgid and terminal control signals with tcsetpgrp so background processes don't steal terminal input.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
I'm creating a simplified C Unix shell demonstrating job control with Ctrl+Z, fg, bg commands, managing process groups via setpgid and terminal control via tcsetpgrp, including signal handling and a basic job list.
Below is a minimal, educational example of a tiny interactive shell that supports basic job control: launching foreground/background jobs, stopping them with Ctrl+Z, and resuming them with fg and bg. It uses setpgid to put each job in its own process group and tcsetpgrp to pass terminal control to foreground jobs so background jobs don’t steal input.
Note: This is a simplified demonstration. Real shells handle a lot more edge cases (signals, pipelines, I/O redirection, job numbering, etc.), and their signal handlers avoid non‑async‑safe calls. This code aims to be as clear as possible for learning purposes.
c
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <termios.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#define MAX_JOBS 64
#define CMDLINE_MAX 1024
enum job_state { RUNNING, STOPPED, DONE };
struct job {
int id; // job ID for shell
pid_t pgid; // process group ID
enum job_state st; // RUNNING, STOPPED, DONE
char cmd[CMDLINE_MAX];
};
static struct job jobs[MAX_JOBS];
static int num_jobs = 0;
static pid_t shell_pgid;
static int shell_terminal;
static struct termios shell_tmodes;
static int shell_interactive;
/* Find job by pgid or job ID */
static struct job* find_job_by_pgid(pid_t pgid) {
for (int i=0; i<num_jobs; ++i) {
if (jobs[i].pgid == pgid) return &jobs[i];
}
return NULL;
}
static struct job* find_job_by_id(int jid) {
for (int i=0; i<num_jobs; ++i) {
if (jobs[i].id == jid) return &jobs[i];
}
return NULL;
}
/* Remove jobs marked DONE */
static void reap_done_jobs(void) {
for (int i=0; i<num_jobs;) {
if (jobs[i].st == DONE) {
// shift down
for (int j=i; j<num_jobs-1; ++j) {
jobs[j] = jobs[j+1];
}
num_jobs--;
} else {
i++;
}
}
}
/* Simple job list printer */
static void print_jobs(void) {
for (int i=0; i<num_jobs; ++i) {
const char* state =
(jobs[i].st == RUNNING) ? "Running" :
(jobs[i].st == STOPPED) ? "Stopped" : "Done";
printf("[%d] (%d) %s\t%s\n",
jobs[i].id, (int)jobs[i].pgid, state, jobs[i].cmd);
}
}
/* Install a child status handler */
static void sigchld_handler(int sig) {
(void)sig;
int status;
pid_t pid;
// Reap all finished/stopped children
while ((pid = waitpid(-1, &status, WNOHANG|WUNTRACED|WCONTINUED)) > 0) {
struct job* jb = find_job_by_pgid(pid);
if (!jb) {
// if pid isn't group leader, find its group leader.
jb = find_job_by_pgid(getpgid(pid));
}
if (jb) {
if (WIFEXITED(status) || WIFSIGNALED(status)) {
jb->st = DONE;
} else if (WIFSTOPPED(status)) {
jb->st = STOPPED;
} else if (WIFCONTINUED(status)) {
jb->st = RUNNING;
}
}
}
}
/* Ignore signals that we don't want to be handled by the shell itself */
static void init_shell(void) {
shell_terminal = STDIN_FILENO;
shell_interactive = isatty(shell_terminal);
if (!shell_interactive) return;
// Put shell in its own process group
while (tcgetpgrp(shell_terminal) != (shell_pgid = getpgrp())) {
kill(-shell_pgid, SIGTTIN);
}
signal(SIGINT, SIG_IGN);
signal(SIGQUIT, SIG_IGN);
signal(SIGTSTP, SIG_IGN);
signal(SIGTTIN, SIG_IGN);
signal(SIGTTOU, SIG_IGN);
struct sigaction sa;
sa.sa_handler = sigchld_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
sigaction(SIGCHLD, &sa, NULL);
shell_pgid = getpid();
if (setpgid(shell_pgid, shell_pgid) < 0) {
perror("Couldn't put the shell in its own process group");
exit(1);
}
tcsetpgrp(shell_terminal, shell_pgid);
tcgetattr(shell_terminal, &shell_tmodes);
}
/* Put job into background: just send SIGCONT if stopped */
static void put_job_in_background(struct job* jb, int cont) {
if (cont && jb->st == STOPPED) {
if (kill(-jb->pgid, SIGCONT) < 0) perror("kill (SIGCONT)");
jb->st = RUNNING;
}
}
/* Put job into foreground: give terminal, wait until done or stopped */
static void put_job_in_foreground(struct job* jb, int cont) {
// Set controlling terminal to this job's group
tcsetpgrp(shell_terminal, jb->pgid);
if (cont && jb->st == STOPPED) {
if (kill(-jb->pgid, SIGCONT) < 0) perror("kill (SIGCONT)");
}
// Wait for job to leave foreground
int status;
pid_t pid;
do {
pid = waitpid(-jb->pgid, &status, WUNTRACED);
} while (!WIFEXITED(status) && !WIFSIGNALED(status) && !WIFSTOPPED(status));
// Restore shell to foreground
tcsetpgrp(shell_terminal, shell_pgid);
// Update job status
if (WIFSTOPPED(status)) {
jb->st = STOPPED;
} else {
jb->st = DONE;
}
// Reap if done
reap_done_jobs();
// Restore terminal modes
tcgetattr(shell_terminal, &shell_tmodes);
tcsetattr(shell_terminal, TCSADRAIN, &shell_tmodes);
}
/* Launch a program in foreground/background */
static void launch_job(char** argv, int bg, const char* cmdline) {
pid_t pid;
pid = fork();
if (pid < 0) {
perror("fork");
return;
}
if (pid == 0) {
// Child
pid_t cpid = getpid();
setpgid(cpid, cpid); // Put in new group
// Give terminal to child if foreground
if (!bg) {
tcsetpgrp(shell_terminal, cpid);
}
// Reset signal handlers to defaults
signal(SIGINT, SIG_DFL);
signal(SIGQUIT, SIG_DFL);
signal(SIGTSTP, SIG_DFL);
signal(SIGTTIN, SIG_DFL);
signal(SIGTTOU, SIG_DFL);
signal(SIGCHLD, SIG_DFL);
execvp(argv[0], argv);
perror("execvp");
_exit(1);
} else {
// Parent
setpgid(pid, pid); // set child's group
// Add to job list
if (num_jobs < MAX_JOBS) {
jobs[num_jobs].id = (num_jobs == 0) ? 1 : jobs[num_jobs-1].id + 1;
jobs[num_jobs].pgid = pid;
jobs[num_jobs].st = RUNNING;
strncpy(jobs[num_jobs].cmd, cmdline, CMDLINE_MAX-1);
jobs[num_jobs].cmd[CMDLINE_MAX-1] = '\0';
num_jobs++;
} else {
fprintf(stderr, "Too many jobs\n");
}
if (!bg) {
// Put in foreground
put_job_in_foreground(find_job_by_pgid(pid), 0);
} else {
// Leave in background
printf("[%d] %d\n", jobs[num_jobs-1].id, pid);
}
}
}
/* Very simple parser: split on whitespace */
static int parse_line(char* line, char** argv, int maxargs) {
int argc = 0;
char* token = strtok(line, " \t\r\n");
while (token && argc < maxargs-1) {
argv[argc++] = token;
token = strtok(NULL, " \t\r\n");
}
argv[argc] = NULL;
return argc;
}
int main(void) {
init_shell();
char *line = NULL;
size_t len = 0;
for (;;) {
reap_done_jobs();
printf("mini-shell> ");
fflush(stdout);
if (getline(&line, &len, stdin) == -1) {
if (feof(stdin)) break;
if (errno == EINTR) continue;
perror("getline");
continue;
}
// skip empty line
if (line[0] == '\n' || line[0] == '\0') continue;
// Make a copy of the line for job command string
char cmdcopy[CMDLINE_MAX];
strncpy(cmdcopy, line, CMDLINE_MAX-1);
cmdcopy[CMDLINE_MAX-1] = '\0';
char* argv[64];
int argc = parse_line(line, argv, 64);
if (argc == 0) continue;
/* Builtins: exit, jobs, fg, bg */
if (strcmp(argv[0], "exit") == 0) {
break;
} else if (strcmp(argv[0], "jobs") == 0) {
print_jobs();
continue;
} else if (strcmp(argv[0], "fg") == 0) {
if (argc < 2) {
fprintf(stderr, "fg: job id required\n");
continue;
}
int jid = atoi(argv[1]);
struct job* jb = find_job_by_id(jid);
if (!jb) {
fprintf(stderr, "fg: no such job\n");
continue;
}
put_job_in_foreground(jb, 1);
continue;
} else if (strcmp(argv[0], "bg") == 0) {
if (argc < 2) {
fprintf(stderr, "bg: job id required\n");
continue;
}
int jid = atoi(argv[1]);
struct job* jb = find_job_by_id(jid);
if (!jb) {
fprintf(stderr, "bg: no such job\n");
continue;
}
put_job_in_background(jb, 1);
continue;
}
// Check if command ends with '&' => background
int bg = 0;
if (argv[argc-1][0] == '&') {
bg = 1;
argv[argc-1] = NULL; // remove '&'
}
launch_job(argv, bg, cmdcopy);
}
free(line);
return 0;
}
How it works:
At startup, the shell makes itself a process group leader, grabs the controlling terminal, and ignores job‑control signals (so they go to children instead).
Each new command is forked; the child calls setpgid to create a new process group. Foreground jobs get control of the terminal via tcsetpgrp.
Pressing Ctrl+Z sends SIGTSTP to the foreground process group, stopping it. The shell detects stopped jobs via waitpid/SIGCHLD and marks them STOPPED.
fg <jobid> moves a stopped background job into the foreground (tcsetpgrp) and continues it with SIGCONT if needed, then waits for it.
bg <jobid> sends SIGCONT to a stopped job and leaves it in the background.
jobs prints the current job list.
Compile with gcc -o mini-shell mini-shell.c and run it in a terminal. This is a starting point; real shells do more error checking and handle pipelines, redirections, and many corner cases.