C โปรเจกต์: mini shell



เขียน shell แบบง่าย ที่รันได้จริง — พิมพ์ ls -l, echo hello, cd /tmp เข้าใจว่า bash/zsh ทำงานยังไงเบื้องหลัง

โปรเจกต์นี้ใช้ POSIX (<unistd.h>, <sys/wait.h>) — รันบน Linux / macOS / WSL

ขอบเขตของ mini shell นี้: รองรับคำสั่งเดี่ยว + argument, built-in cd/exit/pwd, และตรวจความยาวบรรทัด/จำนวน token — ยังไม่มี quote/escape, pipe (|), redirection (>/<), job control, หรือ $VAR expansion (เป็นงานต่อยอดท้ายบท)

shell ทำอะไร (วนลูป)

1. พิมพ์ prompt  "mysh> "
2. อ่านบรรทัดคำสั่งจากผู้ใช้
3. แยกเป็น token: "ls -l /tmp" → ["ls", "-l", "/tmp"]
4. ถ้าเป็น built-in (cd, exit) → ทำเอง
5. ไม่ใช่ → fork() สร้าง process ลูก
6.   ลูก: execvp() แทนที่ตัวเองด้วยโปรแกรมที่ขอ
7.   พ่อ: waitpid() รอลูกจบ
8. กลับไปข้อ 1

mysh.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>

#define MAX_LINE   1024
#define MAX_ARGS   64

// แยกบรรทัดเป็น token ด้วย whitespace, เขียน pointer ลง argv[], ปิดด้วย NULL
// คืนจำนวน token, หรือ -1 ถ้ามีมากกว่า max-1 (ไม่ตัดเงียบ ๆ)
static int tokenize(char *line, char *argv[], int max)
{
    int argc = 0;
    char *tok = strtok(line, " \t\r\n");
    while (tok != NULL) {
        if (argc >= max - 1) {
            return -1;                 // token เกิน — ให้ผู้เรียกปฏิเสธทั้งบรรทัด
        }
        argv[argc++] = tok;
        tok = strtok(NULL, " \t\r\n");
    }
    argv[argc] = NULL;                 // execvp ต้องการ NULL ปิดท้าย
    return argc;
}

// built-in: คืน 1 ถ้าจัดการแล้ว (เขียนผลลง *status), 0 ถ้าไม่ใช่ built-in
static int run_builtin(int argc, char *argv[], int *should_exit, int *status)
{
    if (strcmp(argv[0], "exit") == 0) {
        *should_exit = 1;
        if (argc > 1) *status = atoi(argv[1]);   // exit [n] — ไม่ระบุ = ใช้ status ล่าสุด
        return 1;
    }

    if (strcmp(argv[0], "cd") == 0) {
        const char *dir = (argc > 1) ? argv[1] : getenv("HOME");
        if (dir == NULL) dir = "/";
        if (chdir(dir) != 0) {
            fprintf(stderr, "cd: %s: %s\n", dir, strerror(errno));
            *status = 1;
        } else {
            *status = 0;
        }
        return 1;
    }

    if (strcmp(argv[0], "pwd") == 0) {
        char buf[MAX_LINE];
        if (getcwd(buf, sizeof(buf))) {
            printf("%s\n", buf);
            *status = 0;
        } else {
            perror("pwd");
            *status = 1;
        }
        return 1;
    }

    return 0;                          // ไม่ใช่ built-in
}

// รันโปรแกรมภายนอก
static int run_external(char *argv[])
{
    pid_t pid = fork();

    if (pid < 0) {
        perror("fork");
        return -1;
    }

    if (pid == 0) {
        // --- process ลูก ---
        execvp(argv[0], argv);         // แทนที่ตัวเองด้วยโปรแกรมใหม่
        // มาถึงตรงนี้ = execvp ล้มเหลว (โปรแกรมไม่มี, ไม่มีสิทธิ์)
        fprintf(stderr, "%s: %s\n", argv[0], strerror(errno));
        _exit(127);                    // _exit ไม่ flush stdio ของพ่อ
    }

    // --- process พ่อ ---
    int status;
    if (waitpid(pid, &status, 0) < 0) {
        perror("waitpid");
        return -1;
    }

    if (WIFEXITED(status)) {
        return WEXITSTATUS(status);    // exit code ของโปรแกรมที่รัน
    }
    if (WIFSIGNALED(status)) {
        fprintf(stderr, "ถูกฆ่าด้วย signal %d\n", WTERMSIG(status));
        return 128 + WTERMSIG(status);
    }
    return 0;
}

int main(void)
{
    char line[MAX_LINE];
    char *argv[MAX_ARGS];
    int last_status = 0;
    int should_exit = 0;

    while (!should_exit) {
        printf("mysh> ");
        fflush(stdout);

        if (fgets(line, sizeof(line), stdin) == NULL) {
            printf("\n");              // Ctrl+D
            break;
        }

        if (strchr(line, '\n') == NULL && !feof(stdin)) {
            fprintf(stderr, "บรรทัดยาวเกิน %d ตัว — ข้าม\n", MAX_LINE - 1);
            int c;
            while ((c = getchar()) != '\n' && c != EOF) { }   // ทิ้งส่วนที่เหลือของบรรทัด
            last_status = 1;
            continue;
        }

        // สำเนาไว้ก่อน tokenize (strtok แก้ในตัว) — ที่นี่ไม่ต้อง เพราะไม่ใช้ line ต่อ
        int argc = tokenize(line, argv, MAX_ARGS);
        if (argc < 0) {
            fprintf(stderr, "argument เยอะเกิน %d — ข้ามทั้งบรรทัด\n", MAX_ARGS - 1);
            last_status = 1;
            continue;
        }
        if (argc == 0) {
            continue;                  // บรรทัดว่าง
        }

        if (run_builtin(argc, argv, &should_exit, &last_status)) {
            continue;
        }

        last_status = run_external(argv);
    }

    return last_status;
}

Makefile

CC = gcc
CFLAGS = -std=c17 -Wall -Wextra -g -fsanitize=address,undefined

mysh: mysh.c
	$(CC) $(CFLAGS) -o $@ $<

.PHONY: clean
clean:
	rm -f mysh

รัน

make
./mysh
mysh> echo hello from my shell
hello from my shell
mysh> ls
Makefile  mysh  mysh.c
mysh> pwd
/home/user/mysh
mysh> cd /tmp
mysh> pwd
/tmp
mysh> nonexistent-command
nonexistent-command: No such file or directory
mysh> exit

fork / exec / wait — หัวใจ

  • fork() — สร้างสำเนาของ process ปัจจุบัน คืน สองครั้ง: ในพ่อคืน PID ของลูก, ในลูกคืน 0 (จุดนี้แหวกความคุ้นเคย — ฟังก์ชันเดียวคืนสองที่)
  • execvp(prog, argv) — แทนที่ โค้ดของ process ปัจจุบันด้วยโปรแกรม prog — ถ้าสำเร็จ จะ ไม่ return (โค้ดหลัง execvp = execvp ล้มเหลว) p = หาใน $PATH, v = argv เป็น array
  • waitpid(pid, &status, 0) — พ่อรอลูกจบ, status มีข้อมูลว่าลูกจบยังไง (แกะด้วย WIFEXITED/WEXITSTATUS)

ทำไมต้อง fork ก่อน exec: exec ทำลาย process เดิม ถ้า shell exec ตรง ๆ shell ก็หายไป — จึง fork ลูกออกมาให้ลูก exec (ตายแทน) แล้วพ่อ (shell) รอด

ทำไม _exit ไม่ใช่ exit ในลูก

exit() flush stdio buffer และเรียก atexit handlers — buffer พวกนี้ แชร์กับพ่อจาก fork ถ้าลูกเรียก exit() อาจ flush ข้อมูลที่พ่อ buffer ไว้ซ้ำ ใช้ _exit() ในลูกหลัง exec ล้มเหลว

จุดที่ใช้ความรู้จากบทก่อน

ส่วนบท
fgets อ่านบรรทัด, loop จน EOF (Ctrl+D)22, 24
strtok แยก token (แก้ string ในตัว)10
argv[] ปิดด้วย NULL16, 24
strcmp เทียบคำสั่ง10
strerror(errno), perror32
exit code, WEXITSTATUS24
fflush(stdout) ก่อนอ่าน (prompt โผล่ก่อน)22

ต่อยอด

  • redirect — ls > out.txt: ตรวจ token >, open() ไฟล์, dup2() แทน stdout ในลูกก่อน exec
  • pipe — ls | grep .c: pipe() สร้าง 2 fd, fork สองลูก, dup2 ต่อ stdout ตัวแรกเข้า stdin ตัวสอง
  • background — sleep 5 &: ไม่ waitpid ทันที เก็บ PID ไว้ reap ทีหลัง
  • signal — จับ SIGINT (Ctrl+C) ไม่ให้ shell ตาย แต่ส่งต่อให้ process ที่กำลังรัน
  • history, tab completion (ใช้ readline library), environment variable expansion ($HOME)

เรื่องที่คนมักพลาด

  • exec โดยไม่ fork — process ปัจจุบันหายไป (shell ตาย)
  • โค้ดหลัง execvp คิดว่ารันปกติ — รันเฉพาะเมื่อ execvp ล้มเหลว ต้องมี error + _exit
  • ไม่ waitpid — ลูกกลายเป็น zombie (ยัง occupy slot ใน process table)
  • ใช้ exit() แทน _exit() ในลูก — flush buffer ที่แชร์กับพ่อ output ซ้ำ
  • strtok แก้ line ในตัว — ถ้าต้องใช้ line ต่อ ทำสำเนาก่อน
  • ลืม fflush(stdout) หลังพิมพ์ prompt — prompt ค้างใน buffer โผล่หลังผู้ใช้พิมพ์
  • argv[] ไม่ปิดด้วย NULL — execvp อ่านเลยขอบ array
  • fork() คืน -1 ไม่เช็ค — ระบบ process เต็ม แล้วโค้ดทำงานผิด
  • บรรทัดยาวเกิน buffer — fgets อ่านแค่บางส่วน รอบถัดไปอ่านที่เหลือเป็นคำสั่งใหม่ ตรวจว่ามี \n ไหม ถ้าไม่มีให้ทิ้งส่วนที่เหลือ + ปฏิเสธ
  • token เกิน MAX_ARGS — tokenize เดิมตัดเงียบ ๆ (รันคำสั่งผิดจากที่ป้อน) ให้คืน -1 แล้วปฏิเสธทั้งบรรทัด
  • built-in ไม่อัปเดต last_status — cd ที่ล้มเหลวยังทำให้ shell ออกด้วย 0; ให้ built-in เขียนผลลง last_status เหมือน external

สรุป

  • shell loop: prompt → fgets → strtok เป็น argv[] (ปิด NULL) → built-in หรือ external
  • built-in (cd, exit, pwd) ต้องทำในตัว shell เอง (cd ต้องเปลี่ยน cwd ของ shell ไม่ใช่ลูก) และอัปเดต exit status เหมือนคำสั่งภายนอก
  • ตรวจ ความยาวบรรทัด และ จำนวน token ก่อนรัน — ปฏิเสธทั้งบรรทัดถ้าเกิน ไม่รันบางส่วน
  • external: fork() → ลูก execvp(argv[0], argv) (ไม่ return ถ้าสำเร็จ) → พ่อ waitpid() → WEXITSTATUS
  • ลูกที่ exec ล้มเหลว: error ไป stderr + _exit(127) (ไม่ exit)
  • fflush(stdout) ก่อนอ่าน input เสมอ

จบซีรีส์ C — จาก printf("hello") ถึง pointer, malloc, linked list, hash map, และ shell ที่รันได้จริง คุณเข้าใจแล้วว่าหน่วยความจำ, process, และการคอมไพล์ทำงานยังไงในระดับที่ภาษาอื่นซ่อนไว้ — ความรู้นี้ทำให้ทุกภาษาที่เรียนต่อจากนี้ “ใส” ขึ้น และเปิดประตูสู่งาน systems, embedded, และ C++