2013-02-10 37 views
1

我想用vala来启动一个外部应用程序,使用GLib和spawn_command_line_sync()。 根据文档(http://valadoc.org/#!api=glib-2.0/GLib.Process.spawn_sync),您可以传递一个字符串来存储外部应用程序的输出。重定向输出以glib开头的外部应用程序

虽然这工作正常,当启动脚本打印几行,我需要调用一个程序,将打印二进制文件的内容。我有什么办法可以接收外部程序的输出不是在一个字符串,但在一个DataStream或类似的东西?有没有什么办法可以接收外部程序的输出不是在一个字符串,但在一个DataStream或类似的东西?我打算把外部程序的输出写到一个文件中,所以只需调用“cat/usr/bin/apt-get> outputfile”就可以替代(不是很好),但它不会“ t似乎工作。

无论如何,我宁愿它得到某种输出流。 我将不胜感激任何帮助。使用

代码IM:

using GLib; 

static void main(string[] args) { 
    string execute = "cat /usr/bin/apt-get"; 
    string output = "out"; 

    try { 
     GLib.Process.spawn_command_line_sync(execute, out output); 
    } catch (SpawnError e) { 
     stderr.printf("spawn error!"); 
     stderr.printf(e.message); 
    } 

    stdout.printf("Output: %s\n", output); 
} 

回答

2

GLib.Process.spawn_async_with_pipes可以让你做到这一点。它产生进程并为stdoutstderrstdin中的每一个返回文件描述符。 ValaDoc中有一个代码示例,介绍如何设置IOChannel来监视输出。

1

谢谢你,我必须重读spawn_async_with_pipes()返回ints而不是字符串。

这样做有什么问题吗? (除1缓冲区大小)

using GLib; 

static void main(string[] args) { 

    string[] argv = {"cat", "/usr/bin/apt-get"}; 
    string[] envv = Environ.get(); 
    int child_pid; 
    int child_stdin_fd; 
    int child_stdout_fd; 
    int child_stderr_fd; 

    try { 
     Process.spawn_async_with_pipes(
      ".", 
      argv, 
      envv, 
      SpawnFlags.SEARCH_PATH, 
      null, 
      out child_pid, 
      out child_stdin_fd, 
      out child_stdout_fd, 
      out child_stderr_fd); 

    } catch (SpawnError e) { 
     stderr.printf("spawn error!"); 
     stderr.printf(e.message); 
     return; 
    } 

    FileStream filestream1 = FileStream.fdopen(child_stdout_fd, "r"); 
    FileStream filestream2 = FileStream.open("./stdout", "w"); 

    uint8 buf[1]; 
    size_t t; 
    while ((t = filestream1.read(buf, 1)) != 0) { 
     filestream2.write(buf, 1); 
    } 
} 
+1

无可厚非,但你应该叫'waitpid'或添加一个'ChildWatch'到您的主循环,这样就可以收集你的孩子的存在状态。如果没有,它会变成僵尸,直到你退出并且它被'init'重新获得并收割。 – apmasell 2013-02-10 23:15:27

+0

您可能需要考虑使用GLib.OutputStream.splice(在gio-2.0中)。 – nemequ 2013-02-10 23:18:57

相关问题