Files
spl/nob_popen.h
T

55 lines
1.2 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#ifndef __NOB_POPEN_H__
#define __NOB_POPEN_H__
#include "nob.h"
typedef struct {
Nob_String_Builder out; // stdout 内容
int exit_code; // 实际退出码
bool ok; // 是否成功启动
} Nob_Cmd_Result;
typedef struct {
const char **items;
int capacity;
int count;
} Nob_Files;
// 运行命令,捕获 stdout 和退出码(不支持 stdin 和 stderr)
bool nob_cmd_capture_popen(const char *tname, Nob_Cmd_Result *res) {
memset(res, 0, sizeof(*res));
#ifdef _WIN32
FILE *fp = _popen(tname, "r");
#else
FILE *fp = popen(tname, "r");
#endif
if (!fp) {
nob_log(NOB_ERROR, "popen failed");
return false;
}
// 读取输出到 String_Builder
char buffer[4096];
while (fgets(buffer, sizeof(buffer), fp)) {
nob_sb_append_cstr(&res->out, buffer);
}
// 获取退出码
#ifdef _WIN32
res->exit_code = _pclose(fp);
#else
res->exit_code = pclose(fp);
if (WIFEXITED(res->exit_code))
res->exit_code = WEXITSTATUS(res->exit_code);
#endif
res->ok = true;
return true;
}
#define nob_cmd_result_free(res) nob_sb_free((res).out)
#endif /* __NOB_POPEN_H__ */