glib-2.0 : g_spawn_command_line_sync() - unknown stdout length

标签 glib

函数 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/

相关文章:

c - g_key_file_get_string() 如何工作?

c - 将数组存储在 Gvariant 中以用于 GSettings

windows - 无法在 Windows 上使用 Rust 和 GTK 运行 pkg-config

datetime - 为什么是 "error: invalid escape sequence?"

linux - 在 Linux 上运行 openwebrtc 应用程序

python - 如何使用 libSoup 和 GI 发出 HTTP GET 请求?

python - tkinter 与 glib mainloop 的集成

c - 如何使 GLib 强制使用命令行选项?

c++ - 在 Qt 中禁用 Glib 事件循环 - QT_NO_GLIB 未生效

c++ - 是否可以使用 gtkmm 定义 GTK+ 类型?