函数 g_spawn_command_line_sync()
具有参数“gchar **standard_output”
:
https://developer.gnome.org/glib/stable/glib-Spawning-Processes.html#g-spawn-command-line-sync
我需要从standard_output读取二进制数据,但我不知道standard_output的长度。
Function g_spawn_command_line_sync():
http://fossies.org/dox/glib-2.38.2/gspawn-win32_8c_source.html#l01452
执行:
GString *outstr = NULL;
*standard_output = g_string_free (outstr, FALSE);
结构体 GString 包含“gsize len”
,但 g_spawn_command_line_sync()
只能访问 “gchar **”
。
我有下一个解决方案。我将 size of stdout
写入 stderr
,但没有使用。
示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>
int main()
{
gint exit_status = 0;
gchar *p_stdout = NULL;
gchar *p_stderr = NULL;
GError *p_error = NULL;
gboolean result;
result = g_spawn_command_line_sync("./make_image.py", &p_stdout, &p_stderr, &exit_status, &p_error);
if (!result) {
if (p_error != NULL) {
printf(p_error->message);
}
else {
printf("ERROR: Command not run\n");
}
}
else if (exit_status != 0) {
printf(p_stderr);
}
else {
int size = atoi(p_stderr);
gchar *p_c = p_stdout;
for (int i = 0; i < size; ++i) {
fputc(*p_c++, stdout);
}
//printf(p_stdout);
}
if (p_stdout) {
g_free(p_stdout);
}
if (p_stderr) {
g_free(p_stderr);
}
if (p_error) {
g_error_free(p_error);
}
return 0;
}
最佳答案
使用g_spawn_async_with_pipes 。从文件描述符读取二进制数据很容易。如果您确实需要检测子进程何时退出,请使用 g_child_watch_add 添加回调或g_child_watch_add_full ,但是您可能可以只读取描述符,直到它返回错误为止。
关于glib-2.0 : g_spawn_command_line_sync() - unknown stdout length,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24265810/