异步读取子进程 stdin/stderr 结果到 Vala 中的字符串
Async read a subprocess stdin/stderr results into strings in Vala
我尝试从子进程中将 stdin 和 stderr 读入字符串。我请求管道,退出代码为 0(成功),但字符串为空。
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);
为什么没有从 InputStream 读取到字符串 (outStr, errStr)?
该方法无效,因为 string.data
不适合以这种方式使用。相反,应该使用 DataInputStream
来提供类似 read_line()
的功能。参见 details here。
var dis = new DataInputStream(grep.get_stdout_pipe());
在我的例子中,我还需要控制子进程的环境,所以你必须使用 GLib.Process.spawn_async_with_pipes()
而不是 Subprocess
。参见 details here。
我尝试从子进程中将 stdin 和 stderr 读入字符串。我请求管道,退出代码为 0(成功),但字符串为空。
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);
为什么没有从 InputStream 读取到字符串 (outStr, errStr)?
该方法无效,因为 string.data
不适合以这种方式使用。相反,应该使用 DataInputStream
来提供类似 read_line()
的功能。参见 details here。
var dis = new DataInputStream(grep.get_stdout_pipe());
在我的例子中,我还需要控制子进程的环境,所以你必须使用 GLib.Process.spawn_async_with_pipes()
而不是 Subprocess
。参见 details here。