我尝试使用以下函数从 Vala 中的代码执行此外部命令:
https://valadoc.org/glib-2.0/GLib.Process.spawn_command_line_sync.html
命令如下:ping -c 1 191.98.144.1 | cut -d '/' -s -f5
此命令返回毫秒数。
我想捕获变量中的输出数据,但它给了我以下错误:
ping: unknown host |
这是我的代码:
public static int main (string[] args) {
string command_out;
try {
Process.spawn_command_line_sync ("ping -c 1 191.98.144.1 | cut -d '/' -s -f5", out command_out);
stdout.printf ("stdout: " + command_out);
} catch (SpawnError e) {
stdout.printf ("Error: %s\n", e.message);
}
return 0;
}
我做错了什么。非常感谢您的帮助。
最佳答案
您不能只使用 |
运行管道(使用 >
、 <
、 spawn_command_line_sync
等) .
管道是由 shell 进程实现的功能。
解决这个问题的一个简单方法是实际生成一个 shell 进程:
Process.spawn_command_line_sync ("sh -c \"ping -c 1 191.98.144.1 | cut -d '/' -s -f5\"", out command_out);
您必须小心这里的引号。
关于sh - 在 Vala 中执行外部命令不会返回所需的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49678670/