在 Vala 中执行外部命令不会 return 所需的数据

Executing an external command in Vala does not return the desired data

我尝试使用以下函数从我在 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

这个命令returns我毫秒。

我想在变量中捕获输出数据,但出现以下错误:

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);

你必须小心这里的引号。