system() 返回值為 **16 位元整數**,高位元組為訊號/退出碼,低位元組通常為 0。
256 = 1 << 8 → **高位元組 = 1,低位元組 = 0** → 子進程 **正常退出,退出碼 = 1**。
// 簡化邏輯
pid = fork();
if (pid == 0) { // 子進程
execl("/bin/sh", "sh", "-c", command, (char*)0);
_exit(127); // execl 失敗
} else { // 父進程
waitpid(pid, &status, 0);
if (WIFEXITED(status)) return WEXITSTATUS(status) << 8; // 正常退出
if (WIFSIGNALED(status)) return WTERMSIG(status); // 訊號終止
}
ImportError、模組路徑錯誤 (系統 Python vs 虛擬環境)。sys.exit(1)、未捕獲例外。system() 繼承的環境變數 (PATH, PYTHONPATH) 與互動式 Shell 不同。python script.py 在 system() 中解析為 /current/working/dir/script.py。printf("CMD: %s\n", cmd); → 複製到終端機實測。popen() 捕獲標準輸出/錯誤:FILE* fp = popen("python /path/script.py 2>&1", "r");
char buf[1024];
while (fgets(buf, sizeof(buf), fp)) printf("%s", buf);
int ret = pclose(fp); // 返回值同 system()
printf("Exit code: %d\n", WEXITSTATUS(ret));
import sys, traceback; sys.excepthook = lambda t,v,tb: traceback.print_exception(t,v,tb) 確保錯誤輸出到 stderr。popen()、pipe()+fork()+exec()。fork() 子進程 execl(),父進程 waitpid(pid, NULL, WNOHANG)。boost::process、Qt::QProcess、Python subprocess (若主程式為 Python)。