7

I would like to execute a command (like ls) in Vala, like the Python os.system function, or, better, the popen function. Any idea ?

NowhereToHide
  • 353
  • 2
  • 7

3 Answers3

18

OK, got it : Glib.Process.spawn_command_line_sync.

NowhereToHide
  • 353
  • 2
  • 7
12

It's best to use the package posix. Then, just do Posix.system("command") which returns an int.

http://www.valadoc.org/posix/Posix.system.html

jcao219
  • 2,510
  • 3
  • 19
  • 22
1

You can use the GLib.Process.spawn_command_line_sync as:

public static int main (string[] args) {
    string ls_stdout;
    string ls_stderr;
    int ls_status;

    try {
        Process.spawn_command_line_sync ("ls",
                                    out ls_stdout,
                                    out ls_stderr,
                                    out ls_status);

        // Output: <File list>
        print ("stdout:\n");
        // Output: ````
        print (ls_stdout);
        print ("stderr:\n");
        print (ls_stderr);
        // Output: ``0``
        print ("Status: %d\n", ls_status);
    } catch (SpawnError e) {
        print ("Error: %s\n", e.message);
    }

    return 0;
}
Marcel Kohls
  • 1,092
  • 9
  • 19