I try to execute this external command from my code in Vala using the function:
https://valadoc.org/glib-2.0/GLib.Process.spawn_command_line_sync.html
The command is the following: ping -c 1 191.98.144.1 | cut -d '/' -s -f5
This command returns me the milliseconds.
I want to capture the output data in a variable but it gives me the following error:
ping: unknown host |
This is my code:
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;
}
What am I doing wrong. Thank you very much for your help.
You can't just run a pipe (with |
, >
, <
, etc.) using spawn_command_line_sync
.
Pipes are a feature that is implemented by a shell process.
A simple way to get around this is to actually spawn a shell process:
Process.spawn_command_line_sync ("sh -c \"ping -c 1 191.98.144.1 | cut -d '/' -s -f5\"", out command_out);
You have to be careful with the quotes here.