This is a comprehensive request to build a Unix shell with job control. Let me create a well-structured implementation that covers:
- Basic shell functionality (parsing, executing commands)
- Job control (background/foreground processes)
- Process groups and signal handling
- Terminal control with tcsetpgrp
- Support for Ctrl+Z, fg, and bg commands
- Proper management of job states
I'll break this down into several parts:
- Data structures for managing jobs
- Signal handlers for SIGCHLD, SIGINT, SIGTSTP
- Process group management using setpgid
- Terminal control using tcsetpgrp
- Built-in commands (fg, bg, jobs, etc.)
- Command execution and redirection support
Let me write a comprehensive implementation with good error handling and comments.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <fcntl.h>
#include <termios.h>
#define MAX_JOBS 64
#define MAX_ARGS 64
#define MAX_LINE 1024
// Job states
typedef enum {
FOREGROUND,
BACKGROUND,
STOPPED,
DONE
} JobState;
// Job structure
typedef struct {
pid_t pid;
int job_id;
JobState state;
char *cmd;
} Job;
// Global variables
Job jobs[MAX_JOBS];
int num_jobs = 0;
pid_t shell_pgid;
int next_job_id = 1;
// Function prototypes
void init_shell(void);
void handle_sigchld(int sig);
void handle_sigtstp(int sig);
void handle_sigint(int sig);
void execute_command(char *line);
void add_job(pid_t pid, JobState state, char *cmd);
void remove_job(int job_id);
Job* find_job(int job_id);
Job* find_job_by_pid(pid_t pid);
void list_jobs(void);
void foreground_job(int job_id);
void background_job(int job_id);
void reap_zombies(void);
int parse_command(char *line, char **args);
int main(void)
The main loop initializes the shell, then continuously prompts for input and processes commands until EOF. Each line gets trimmed of its newline and skipped if empty before being passed to execute_command. The shell exits cleanly after the input stream ends.
The initialization sets up signal handlers for SIGINT, SIGTSTP, and SIGCHLD to manage job control, while ignoring SIGTTOU and SIGTTIN to prevent background process interference.
);
shell_pgid = getpid();
if (setpgid(shell_pgid, shell_pgid) < 0) {
perror("setpgid");
exit(1);
}
tcsetpgrp(STDIN_FILENO, shell_pgid);
}
void handle_sigchld(int sig) {
pid_t pid;
int status;
while ((pid = waitpid(-1, &status, WNOHANG | WUNTRACED)) > 0) {
Job *job = find_job_by_pid(pid);
if (job == NULL)
continue;
if (WIFSTOPPED(status)) {
job->state = STOPPED;
printf("\n[%d] Stopped %s\n", job->job_id, job->cmd);
printf("myshell> ");
fflush(stdout);
} else if (WIFEXITED(status) || WIFSIGNALED(status)) {
job->state = DONE;
}
}
}
void handle_sigtstp(int sig) {
// Signal will
The shell places itself in its own process group and takes control of the terminal. When child processes terminate or stop, the SIGCHLD handler reaps them and updates their job state, reprinting the prompt if a job was suspended. The SIGTSTP handler manages background job suspension. return;
} else if (strcmp(args[0], "bg") == 0) {
if (argc < 2) {
fprintf(stderr, "bg: missing job id\n");
} else {
int job_id = atoi(args[1]);
background_job(job_id);
}
return;
}
// Fork and execute
pid = fork();
if (pid < 0) {
perror("fork");
} else if (pid == 0) {
// Child process
// Create new process group for the job
setpgid(0, 0);
// Restore default signal handlers
signal(SIGINT, SIG_DFL);
signal(SIGTSTP, SIG_DFL);
The bg command works similarly to fg, taking a job ID and resuming it in the background. After handling built-in commands, I fork a new process and set up its process group so it can be managed independently. The child process then restores default signal handling.
signal(SIGCHLD, SIG_DFL);
// Execute command
execvp(args[0], args);
perror("execvp");
exit(1);
} else {
// Parent process
// Put child in its own process group
setpgid(pid, pid);
if (background) {
// Background job
add_job(pid, BACKGROUND, line);
printf("[%d] %d %s\n", next_job_id - 1, pid, line);
} else {
// Foreground job
add_job(pid, FOREGROUND, line);
// Give terminal to child process
tcsetpgrp(STDIN_FILENO, pid);
// Wait for child to finish
int status;
do {
waitpid(pid, &status, WUNTRACED);
if (WIFSTOPPED(status)) {
Job *job = find_job_by_pid(pid);
if (job) {
job->state = STOPPED;
printf("\n[%d] Stopped %s\n", job->job_id, job->cmd);
}
break;
}
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
// Give terminal back to shell
tcsetpgrp(STDIN_FILENO, shell_pgid);
// Remove job if it exited
if (WIFEXITED(status) || WIFSIGNALED(status)) {
remove_job(find_job_by_pid(pid)->
In the parent, I register the child as either a background or foreground job. For foreground execution, I transfer terminal control to the child and wait for it to complete, handling stopped processes by updating their state and breaking from the wait loop. Once the child exits or is signaled, I restore terminal control to the shell and clean up the job entry. getpgrp());
if (WIFEXITED(status) || WIFSIGNALED(status)) {
remove_job(job_id);
}
}
void background_job(int job_id) {
Job *job = find_job(job_id);
if (job == NULL) {
fprintf(stderr, "Job %d not found\n", job_id);
return;
}
if (job->state != STOPPED) {
fprintf(stderr, "Job %d is not stopped\n", job_id);
return;
}
job->state = BACKGROUND;
if (kill(-job->pid, SIGCONT) < 0) {
perror("kill");
return;
}
}
I'm noticing a few issues that need addressing. The parse_command function shouldn't deallocate memory in ways that invalidate the argument pointers. Signal handlers need better robustness, and I should ensure foreground job waiting works correctly while also reaping zombie processes. Let me refactor with these concerns in mind.
The revised approach includes proper includes and defines for a job control shell. I'm setting up a Job structure to track processes with their ID, state, and command, along with global tracking for the shell's process group and job counter. Signal handling uses volatile sig_atomic_t for thread-safe flag management, particularly for SIGCHLD events that indicate child process state changes.
The function declarations outline the core operations: command execution, job management (adding, removing, finding), job listing, foreground/background control, and child process reaping. The main loop initializes the shell, then repeatedly prompts for input, parses commands, executes them, and cleans up any terminated children. The init_shell function begins setting up signal handlers to manage job control signals appropriately. NULL)
continue;
if (WIFSTOPPED(status)) {
job->state = STOPPED;
} else if (WIFEXITED(status) || WIFSIGNALED(status)) {
job->state = DONE;
}
}
}
int parse_command(const char *line, char **args) {
int count = 0;
char *token;
char *line_copy = strdup(line);
if (line_copy == NULL) {
fprintf(stderr, "Memory allocation failed\n");
return 0;
}
token = strtok(line_copy, " \t");
while (token != NULL && count < MAX_ARGS - 1) {
args[count] = strdup(token);
if (args[count] == NULL) {
fprintf(stderr, "Memory allocation failed\n");
break;
}
count++;
token = strtok(NULL, " \t");
}
args[count] = NULL;
free(line_copy);
return count;
}
void execute_command(const char *line) {
char *args[MAX_ARGS];
int argc;
int background = 0;
pid_t pid;
argc = parse_command(line, args);
if (argc == 0)
return;
if (argc > 0 && strcmp(args[argc - 1], "&") == 0) {
background = 1;
free(args[argc - 1]);
args[--argc] = NULL;
}
if (argc == 0)
return;
if (strcmp(args[0], "exit") == 0) {
exit(0);
} else if (strcmp(args[0], "jobs") == 0) {
list_jobs();
for (int i = 0; args[i] != NULL; i++)
free(args[i]);
return;
} else if (strcmp(args[0], "fg") == 0) {
if (argc < 2) {
fprintf(stderr, "fg: missing job id\n");
} else {
foreground_job(atoi(args[1]));
}
for (int i = 0; args[i] != NULL; i++)
free(args[i]);
return;
} else if (strcmp(args[0], "bg") == 0) {
if (argc < 2) {
fprintf(stderr, "bg: missing job id\n");
} else {
background_job(atoi(args[1]));
}
for (int i = 0; args[i] != NULL; i++)
free(args[i]);
return;
}
The built-in commands handle exit, job listing, and foreground/background job control. Each command validates its arguments and cleans up allocated memory before returning.
For external commands, I fork a child process and set up a new process group. The child restores default signal handlers and executes the command via execvp. In the parent, I place the child in its own process group, then either add it as a background job with output or add it as foreground and transfer terminal control to it.
For foreground jobs, I wait for the child using waitpid with WUNTRACED to catch stopped processes. Once it returns, I check the status—if stopped, I update the job state and notify the user; if exited normally, I report completion and remove it from the job list; if terminated by signal, I handle that case as well.
After the child finishes, I restore terminal control back to the shell process group before returning. The function also cleans up allocated argument strings and the add_job helper manages inserting new jobs into the tracking array with proper initialization of the job ID, state, and command string.
The remove_job function searches for a matching job ID and frees its command string before shifting remaining jobs down in the array. I also have lookup helpers—find_job searches by job ID while find_job_by_pid searches by process ID. The list_jobs function begins by reaping any terminated child processes. printf("[%d]+ Continuing %s\n", job->job_id, job->cmd);
job->state = FOREGROUND;
// Send SIGCONT to wake up stopped job (negative pid = process group)
if (kill(-job->pid, SIGCONT) < 0) {
if (errno == ESRCH) {
fprintf(stderr, "Process no longer exists\n");
remove_job(job_id);
} else {
perror("kill");
}
return;
}
// Give terminal to job
if (tcsetpgrp(STDIN_FILENO, job->pid) < 0) {
perror("tcsetpgrp");
return;
}
// Wait for job to finish or stop
int status;
I'm sending SIGCONT to the process group to resume the job, then transferring terminal control to it. After that, I need to wait for the job to complete or be stopped again.
I'll use waitpid with WUNTRACED to monitor the job, retrying if interrupted by signals. Once the job finishes, I check its exit status—if it stopped, I update the state; if it exited or was terminated, I remove it from the job list. Finally, I return terminal control back to the shell.
For resuming background jobs, I first verify the job exists and is in a stopped state. I send SIGCONT to the process group to resume execution, handling cases where the process no longer exists. Then I update the job state to BACKGROUND and notify the user.
Now I'm setting up build infrastructure with a Makefile that compiles the shell with appropriate flags and provides clean targets. I should also add input/output redirection support to make this more complete, along with comprehensive documentation and test cases to validate the implementation.
Unix Shell with Job Control
Here's a comprehensive implementation of a Unix shell with job control, process groups, and terminal management:
Main Shell Implementation
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#define MAX_JOBS 64
#define MAX_ARGS 64
#define MAX_LINE 1024
/* Job states */
typedef enum {
FOREGROUND,
BACKGROUND,
STOPPED,
DONE
} JobState;
/* Job structure */
typedef struct {
pid_t pid;
int job_id;
JobState state;
char *cmd;
} Job;
/* Global variables */
Job jobs[MAX_JOBS];
int num_jobs = 0;
pid_t shell_pgid;
int next_job_id = 1;
/* Function prototypes */
void init_shell(void);
void handle_sigchld(int sig);
void handle_sigtstp(int sig);
void handle_sigint(int sig);
void execute_command(const char *line);
void add_job(pid_t pid, JobState state, const char *cmd);
void remove_job(int job_id);
Job* find_job(int job_id);
Job* find_job_by_pid(pid_t pid);
void list_jobs(void);
void foreground_job(int job_id);
void background_job(int job_id);
void reap_dead_children(void);
int parse_command(const char *line, char **args);
void print_prompt(void);
void cleanup_args(char **args);
int main(void) {
char line[MAX_LINE];
init_shell();
while (1) {
print_prompt();
if (fgets(line, sizeof(line), stdin) == NULL) {
printf("\n");
break;
}
/* Remove trailing newline */
line[strcspn(line, "\n")] = 0;
if (strlen(line) == 0)
continue;
execute_command(line);
/* Reap any dead children */
reap_dead_children();
}
/* Cleanup */
for (int i = 0; i < num_jobs; i++) {
if (jobs[i].cmd)
free(jobs[i].cmd);
}
printf("\nExiting shell...\n");
return 0;
}
/**
* Initialize shell: set up signal handlers and process groups
*/
void init_shell(void) {
/* Set up signal handlers */
signal(SIGINT, handle_sigint);
signal(SIGTSTP, handle_sigtstp);
signal(SIGCHLD, handle_sigchld);
signal(SIGTTOU, SIG_IGN);
signal(SIGTTIN, SIG_IGN);
/* Put shell in its own process group */
shell_pgid = getpid();
if (setpgid(shell_pgid, shell_pgid) < 0) {
perror("setpgid");
exit(1);
}
/* Give terminal to shell */
if (tcsetpgrp(STDIN_FILENO, shell_pgid) < 0) {
perror("tcsetpgrp");
exit(1);
}
printf("Simple Unix Shell with Job Control\n");
printf("Commands: fg <id>, bg <id>, jobs, exit\n");
printf("Use Ctrl+Z to suspend, Ctrl+C to terminate\n\n");
}
/**
* Handle SIGCHLD: child process stopped or exited
*/
void handle_sigchld(int sig) {
/* Reaping is done in main loop */
(void)sig;
}
/**
* Handle SIGTSTP: Ctrl+Z pressed
* This signal goes to the foreground process group
*/
void handle_sigtstp(int sig) {
/* Default behavior for child process */
(void)sig;
}
/**
* Handle SIGINT: Ctrl+C pressed
* This signal goes to the foreground process group
*/
void handle_sigint(int sig) {
/* Default behavior for child process */
(void)sig;
}
/**
* Reap all dead children and update job states
*/
void reap_dead_children(void) {
pid_t pid;
int status;
while ((pid = waitpid(-1, &status, WNOHANG | WUNTRACED)) > 0) {
Job *job = find_job_by_pid(pid);
if (job == NULL)
continue;
if (WIFSTOPPED(status)) {
job->state = STOPPED;
/* Don't print here - already printed by parent */
} else if (WIFEXITED(status) || WIFSIGNALED(status)) {
job->state = DONE;
}
}
}
/**
* Parse command line into arguments
* Returns number of arguments parsed
*/
int parse_command(const char *line, char **args) {
int count = 0;
char *token;
char *line_copy = strdup(line);
if (line_copy == NULL) {
fprintf(stderr, "Memory allocation failed\n");
return 0;
}
token = strtok(line_copy, " \t");
while (token != NULL && count < MAX_ARGS - 1) {
args[count] = strdup(token);
if (args[count] == NULL) {
fprintf(stderr, "Memory allocation failed\n");
break;
}
count++;
token = strtok(NULL, " \t");
}
args[count] = NULL;
free(line_copy);
return count;
}
/**
* Clean up allocated argument strings
*/
void cleanup_args(char **args) {
for (int i = 0; args[i] != NULL; i++)
free(args[i]);
}
/**
* Print shell prompt with last job status
*/
void print_prompt(void) {
/* Clean up any DONE jobs first */
for (int i = num_jobs - 1; i >= 0; i--) {
if (jobs[i].state == DONE) {
printf("[%d]+ Done %s\n", jobs[i].job_id, jobs[i].cmd);
remove_job(jobs[i].job_id);
}
}
printf("myshell> ");
fflush(stdout);
}
/**
* Execute a command: built-in or external
*/
void execute_command(const char *line) {
char *args[MAX_ARGS];
int argc;
int background = 0;
pid_t pid;
argc = parse_command(line, args);
if (argc == 0)
return;
/* Check if command should run in background */
if (argc > 0 && strcmp(args[argc - 1], "&") == 0) {
background = 1;
free(args[argc - 1]);
args[--argc] = NULL;
}
/* Verify we still have a command */
if (argc == 0)
return;
/* ============== Handle built-in commands ============== */
if (strcmp(args[0], "exit") == 0) {
cleanup_args(args);
exit(0);
}
else if (strcmp(args[0], "jobs") == 0) {
list_jobs();
cleanup_args(args);
return;
}
else if (strcmp(args[0], "fg") == 0) {
if (argc < 2) {
fprintf(stderr, "Usage: fg <job_id>\n");
} else {
int job_id = atoi(args[1]);
foreground_job(job_id);
}
cleanup_args(args);
return;
}
else if (strcmp(args[0], "bg") == 0) {
if (argc < 2) {
fprintf(stderr, "Usage: bg <job_id>\n");
} else {
int job_id = atoi(args[1]);
background_job(job_id);
}
cleanup_args(args);
return;
}
else if (strcmp(args[0], "help") == 0) {
printf("Built-in commands:\n");
printf(" jobs - List all jobs\n");
printf(" fg <id> - Bring job to foreground\n");
printf(" bg <id> - Resume job in background\n");
printf(" exit - Exit shell\n");
printf(" help - Show this help\n");
cleanup_args(args);
return;
}
/* ============== Execute external command ============== */
pid = fork();
if (pid < 0) {
perror("fork");
}
else if (pid == 0) {
/* ===== Child process ===== */
/* Create new process group for the job */
if (setpgid(0, 0) < 0) {
perror("setpgid");
exit(1);
}
/* Restore default signal handlers */
signal(SIGINT, SIG_DFL);
signal(SIGTSTP, SIG_DFL);
signal(SIGCHLD, SIG_DFL);
signal(SIGTTOU, SIG_DFL);
signal(SIGTTIN, SIG_DFL);
/* Execute command */
execvp(args[0], args);
perror("execvp");
exit(127);
}
else {
/* ===== Parent process (shell) ===== */
/* Put child in its own process group */
if (setpgid(pid, pid) < 0) {
perror("setpgid");
}
if (background) {
/* Background job */
add_job(pid, BACKGROUND, line);
printf("[%d] %d\n", next_job_id - 1, pid);
}
else {
/* Foreground job - add to job list */
add_job(pid, FOREGROUND, line);
/* Give terminal to child process group */
if (tcsetpgrp(STDIN_FILENO, pid) < 0) {
perror("tcsetpgrp");
}
/* Wait for child to finish or stop */
int status;
pid_t wpid;
do {
wpid = waitpid(pid, &status, WUNTRACED);
if (wpid < 0) {
if (errno == EINTR) {
/* Interrupted by signal, retry */
continue;
} else {
perror("waitpid");
break;
}
}
} while (wpid < 0);
if (wpid > 0) {
Job *job = find_job_by_pid(pid);
if (job) {
if (WIFSTOPPED(status)) {
job->state = STOPPED;
printf("\n[%d]+ Stopped %s\n", job->job_id, job->cmd);
}
else if (WIFEXITED(status)) {
int exit_status = WEXITSTATUS(status);
if (exit_status != 0) {
printf("[%d]+ Done (exit code %d) %s\n",
job->job_id, exit_status, job->cmd);
}
remove_job(job->job_id);
}
else if (WIFSIGNALED(status)) {
int sig = WTERMSIG(status);
printf("[%d]+ Terminated (signal %d) %s\n",
job->job_id, sig, job->cmd);
remove_job(job->job_id);
}
}
}
/* Give terminal back to shell */
if (tcsetpgrp(STDIN_FILENO, shell_pgid) < 0) {
perror("tcsetpgrp");
}
}
}
cleanup_args(args);
}
/**
* Add a new job to the job list
*/
void add_job(pid_t pid, JobState state, const char *cmd) {
if (num_jobs >= MAX_JOBS) {
fprintf(stderr, "Too many jobs\n");
return;
}
jobs[num_jobs].pid = pid;
jobs[num_jobs].job_id = next_job_id++;
jobs[num_jobs].state = state;
jobs[num_jobs].cmd = strdup(cmd);
if (jobs[num_jobs].cmd == NULL) {
fprintf(stderr, "Memory allocation failed\n");
return;
}
num_jobs++;
}
/**
* Remove a job from the job list by job ID
*/
void remove_job(int job_id) {
for (int i = 0; i < num_jobs; i++) {
if (jobs[i].job_id == job_id) {
if (jobs[i].cmd)
free(jobs[i].cmd);
/* Shift remaining jobs */
for (int j = i; j < num_jobs - 1; j++) {
jobs[j] = jobs[j + 1];
}
num_jobs--;
return;
}
}
}
/**
* Find job by job ID
*/
Job* find_job(int job_id) {
for (int i = 0; i < num_jobs; i++) {
if (jobs[i].job_id == job_id)
return &jobs[i];
}
return NULL;
}
/**
* Find job by process ID
*/
Job* find_job_by_pid(pid_t pid) {
for (int i = 0; i < num_jobs; i++) {
if (jobs[i].pid == pid)
return &jobs[i];
}
return NULL;
}
/**
* List all jobs with their statuses
*/
void list_jobs(void) {
if (num_jobs == 0) {
printf("No jobs\n");
return;
}
printf("\n%-5s %-10s %-20s %s\n", "ID", "PID", "STATE", "COMMAND");
printf("%-5s %-10s %-20s %s\n", "--", "---", "-----", "-------");
for (int i = 0; i < num_jobs; i++) {
const char *state_str;
switch (jobs[i].state) {
case FOREGROUND:
state_str = "Running (FG)";
break;
case BACKGROUND:
state_str = "Running (BG)";
break;
case STOPPED:
state_str = "Stopped";
break;
case DONE:
state_str = "Done";
break;
default:
state_str = "Unknown";
}
printf("[%-3d] %-10d %-20s %s\n",
jobs[i].job_id, jobs[i].pid, state_str, jobs[i].cmd);
}
printf("\n");
}
/**
* Bring a stopped job to foreground
* Sends SIGCONT to the process group
*/
void foreground_job(int job_id) {
Job *job = find_job(job_id);
if (job == NULL) {
fprintf(stderr, "fg: job %d not found\n", job_id);
return;
}
if (job->state == DONE) {
fprintf(stderr, "fg: job %d is done\n", job_id);
remove_job(job_id);
return;
}
printf("[%d]+ Continuing %s\n", job->job_id, job->cmd);
job->state = FOREGROUND;
/* Send SIGCONT to the entire process group (negative pid) */
if (kill(-job->pid, SIGCONT) < 0) {
if (errno == ESRCH) {
fprintf(stderr, "Process no longer exists\n");
remove_job(job_id);
} else {
perror("kill");
}
return;
}
/* Give terminal to job's process group */
if (tcsetpgrp(STDIN_FILENO, job->pid) < 0) {
perror("tcsetpgrp");
return;
}
/* Wait for job to finish or stop */
int status;
pid_t wpid;
do {
wpid = waitpid(job->pid, &status, WUNTRACED);
if (wpid < 0) {
if (errno == EINTR) {
continue;
} else {
perror("waitpid");
break;
}
}
} while (wpid < 0);
if (wpid > 0) {
if (WIFSTOPPED(status)) {
job->state = STOPPED;
printf("[%d]+ Stopped %s\n", job->job_id, job->cmd);
}
else if (WIFEXITED(status)) {
printf("[%d]+ Done %s\n", job->job_id, job->cmd);
remove_job(job_id);
}
else if (WIFSIGNALED(status)) {
int sig = WTERMSIG(status);
printf("[%d]+ Terminated (signal %d) %s\n",
job->job_id, sig, job->cmd);
remove_job(job_id);
}
}
/* Give terminal back to shell */
if (tcsetpgrp(STDIN_FILENO, shell_pgid) < 0) {
perror("tcsetpgrp");
}
}
/**
* Resume a stopped job in background
* Sends SIGCONT to the process group
*/
void background_job(int job_id) {
Job *job = find_job(job_id);
if (job == NULL) {
fprintf(stderr, "bg: job %d not found\n", job_id);
return;
}
if (job->state != STOPPED) {
fprintf(stderr, "bg: job %d is not stopped (state: %d)\n",
job_id, job->state);
return;
}
job->state = BACKGROUND;
/* Send SIGCONT to the entire process group (negative pid) */
if (kill(-job->pid, SIGCONT) < 0) {
if (errno == ESRCH) {
fprintf(stderr, "Process no longer exists\n");
remove_job(job_id);
} else {
perror("kill");
}
return;
}
printf("[%d]+ Continued in background %s\n", job->job_id, job->cmd);
}
Makefile
CC = gcc
CFLAGS = -Wall -Wextra -Werror -std=c99 -D_POSIX_C_SOURCE=200809L
LDFLAGS =
TARGET = myshell
SOURCES = myshell.c
OBJECTS = $(SOURCES:.c=.o)
all: $(TARGET)
$(TARGET): $(OBJECTS)
$(CC) $(LDFLAGS) -o $@ $^
%.o: %.c
$(CC) $(CFLAGS) -c -o $@ $<
run: $(TARGET)
./$(TARGET)
clean:
rm -f $(OBJECTS) $(TARGET) *.core
.PHONY: all run clean
Build and Test
# Build
make clean
make
# Run
./myshell
# Or use run target
make run
Usage Examples
myshell> sleep 100
# Press Ctrl+Z to suspend
[1]+ Stopped sleep 100
myshell> jobs
ID PID STATE COMMAND
-- --- ----- -------
[1] 12345 Stopped sleep 100
myshell> bg 1
[1]+ Continued in background sleep 100
myshell> jobs
ID PID STATE COMMAND
-- --- ----- -------
[1] 12345 Running (BG) sleep 100
myshell> sleep 50 &
[2] 12346
myshell> jobs
ID PID STATE COMMAND
-- --- ----- -------
[1] 12345 Running (BG) sleep 100
[2] 12346 Running (BG) sleep 50
myshell> fg 2
[2]+ Continuing sleep 50
# Ctrl+C to terminate
[2]+ Terminated (signal 2) sleep 50
myshell> fg 1
[1]+ Continuing sleep 100
# Ctrl+Z to suspend again
[1]+ Stopped sleep 100
myshell> bg 1
[1]+ Continued in background sleep 100
myshell> help
# Shows available commands
Key Features
| Feature | Implementation |
|---|
| Job Control | Jobs array tracking PID, job ID, state, and command |
| Process Groups | setpgid() creates isolated process groups |
| Terminal Control | tcsetpgrp() switches terminal access between shell and jobs |
| Signal Handling | SIGCHLD for child state changes, passed to children |
| Ctrl+Z Support | SIGTSTP forwarded to foreground process group |
| Ctrl+C Support | SIGINT forwarded to foreground process group |
| Background Execution | & suffix runs command without terminal access |
| fg Command | Brings stopped/background job to foreground with SIGCONT |
| bg Command | Resumes stopped job in background with SIGCONT |
| jobs Command | Lists all active jobs with states |
Important Concepts
- Process Groups: Each job runs in its own process group for isolation
- Terminal Access: Only foreground process group gets terminal input
- Signals Flow: Shell ignores SIGINT/SIGTSTP; they go to foreground group
- Job States: Track running, stopped, and completed processes
- SIGCONT: Resumes stopped processes when moving to foreground/background