Search code examples
asynchronousvala

Async read a subprocess stdin/stderr results into strings in Vala


I try to read stdin and stderr into strings from a subprocess. I request the pipe and the exit code is 0 (success) but the strings are empty.

string errStr = "";
string outStr = "";

string[] cmd = {
    "grep",
    "--help"
};

var grep = new Subprocess.newv(cmd, 
    SubprocessFlags.STDOUT_PIPE|SubprocessFlags.STDERR_PIPE);
yield grep.wait_async();

int exit_code = grep.get_exit_status();

size_t bytes;
yield grep.get_stderr_pipe().read_all_async(errStr.data, 0, null, out bytes);
yield grep.get_stdout_pipe().read_all_async(outStr.data, 0, null, out bytes);

Why is nothing read from the InputStream to strings (outStr, errStr)?


Solution

  • The approach is not working as string.data is not meant to be used this way. Instead a DataInputStream should be used that provides functions like read_line(). See details here.

    var dis = new DataInputStream(grep.get_stdout_pipe());
    

    In my case I also need control over the environment of the subprocess so in then you have to useGLib.Process.spawn_async_with_pipes() instead of Subprocess. See details here.