不呼叫 system() 或 cmd.exe,需自行實作:
fgets(buf, sizeof(buf), stdin)。argv[] 陣列。cd、exit、pwd 等直接在進程內處理。CreateProcess()。fork() + execvp()。WaitForSingleObject() / waitpid()。#include <windows.h>
#include <stdio.h>
#include <string.h>
#define MAX_ARGS 64
#define BUFSIZE 1024
int main()
{
char buf[BUFSIZE];
STARTUPINFO si = { sizeof(si) };
PROCESS_INFORMATION pi;
while (1) {
printf("mysh> ");
if (!fgets(buf, BUFSIZE, stdin)) break;
buf[strcspn(buf, "\n")] = '\0'; // 去換行
if (!*buf) continue;
// 簡易分割 (未處理引號/轉義)
char *argv[MAX_ARGS] = {0};
int argc = 0;
for (char *p = strtok(buf, " "); p && argc < MAX_ARGS-1; p = strtok(NULL, " "))
argv[argc++] = p;
argv[argc] = NULL;
if (strcmp(argv[0], "exit") == 0) break;
if (strcmp(argv[0], "cd") == 0) {
if (argc > 1) SetCurrentDirectoryA(argv[1]);
continue;
}
// 建立命令列字串給 CreateProcess
char cmdline[BUFSIZE] = "";
for (int i = 0; i < argc; i++) {
strcat(cmdline, argv[i]);
if (i+1 < argc) strcat(cmdline, " ");
}
if (CreateProcessA(NULL, cmdline, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
} else {
printf("命令執行失敗: %lu\n", GetLastError());
}
}
return 0;
}
|、重導向 > <、背景執行 &。ReadConsole + 歷史緩衝)。