Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sh

glib

vala

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.

like image 791
Alain Avatar asked May 10 '26 17:05

Alain


1 Answers

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.

like image 135
Jens Mühlenhoff Avatar answered May 15 '26 00:05

Jens Mühlenhoff