From f1957094937fdd5fc330ecdaf0a9ff26afce5e08 Mon Sep 17 00:00:00 2001 From: Aoran Zeng Date: Wed, 20 Aug 2025 19:49:01 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=9E=E7=8E=B0=20`xy=5Frun=5Fcapture()`=20[?= =?UTF-8?q?GitHub=20#268=20#269]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/xy.h | 38 ++++++++++++++++++++++++++++++++++++++ test/xy.c | 2 +- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/lib/xy.h b/lib/xy.h index e02dabf..72ffe3d 100644 --- a/lib/xy.h +++ b/lib/xy.h @@ -815,6 +815,44 @@ xy_run (const char *cmd, unsigned long n) } +/** + * @brief 捕获命令的输出 + * + * @param[in] cmd 要执行的命令 + * @param[out] output 捕获的标准输出 + * + * @return 返回命令的执行状态 + */ +static int +xy_run_capture (const char *cmd, char **output) +{ + int cap = 8192; /* 假如1行100个字符,大约支持80行输出 */ + char *buf = (char *) xy_malloc0 (cap); + + FILE *stream = popen (cmd, "r"); + if (stream == NULL) + { + fprintf (stderr, "xy: 命令执行失败\n"); + return -1; + } + + int size = 0; + size_t n; + while ((n = fread (buf + size, 1, cap - size, stream)) > 0) { + size += n; + if (size == cap) + { + cap *= 2; + char *new_buf = realloc (buf, cap); + buf = new_buf; + } + } + buf[size] = '\0'; + + int status = pclose (stream); + *output = buf; + return status; +} /****************************************************** diff --git a/test/xy.c b/test/xy.c index 57d63fc..a78a1b7 100644 --- a/test/xy.c +++ b/test/xy.c @@ -28,7 +28,7 @@ print_str_for_map (const char *key, void *value) int main (int argc, char const *argv[]) { - xy_useutf8 (); + xy_use_utf8 (); println (xy_os_depend_str ("Hello, Windows!", "Hello, Unix!"));