Skip to content

Commit f195709

Browse files
committed
实现 xy_run_capture()
[GitHub #268 #269]
1 parent 98516e0 commit f195709

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

lib/xy.h

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -815,6 +815,44 @@ xy_run (const char *cmd, unsigned long n)
815815
}
816816

817817

818+
/**
819+
* @brief 捕获命令的输出
820+
*
821+
* @param[in] cmd 要执行的命令
822+
* @param[out] output 捕获的标准输出
823+
*
824+
* @return 返回命令的执行状态
825+
*/
826+
static int
827+
xy_run_capture (const char *cmd, char **output)
828+
{
829+
int cap = 8192; /* 假如1行100个字符,大约支持80行输出 */
830+
char *buf = (char *) xy_malloc0 (cap);
831+
832+
FILE *stream = popen (cmd, "r");
833+
if (stream == NULL)
834+
{
835+
fprintf (stderr, "xy: 命令执行失败\n");
836+
return -1;
837+
}
838+
839+
int size = 0;
840+
size_t n;
841+
while ((n = fread (buf + size, 1, cap - size, stream)) > 0) {
842+
size += n;
843+
if (size == cap)
844+
{
845+
cap *= 2;
846+
char *new_buf = realloc (buf, cap);
847+
buf = new_buf;
848+
}
849+
}
850+
buf[size] = '\0';
851+
852+
int status = pclose (stream);
853+
*output = buf;
854+
return status;
855+
}
818856

819857

820858
/******************************************************

test/xy.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ print_str_for_map (const char *key, void *value)
2828
int
2929
main (int argc, char const *argv[])
3030
{
31-
xy_useutf8 ();
31+
xy_use_utf8 ();
3232

3333
println (xy_os_depend_str ("Hello, Windows!", "Hello, Unix!"));
3434

0 commit comments

Comments
 (0)