How do I open a file in its default program - Linux

前端 未结 3 879
说谎
说谎 2021-01-05 11:06

How do I programmatically open a file in its default program in Linux (im using Ubuntu 10.10).

For example, opening *.mp3 will open the file in Movie Player (or some

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-05 11:55

    You need to run gnome-open, kde-open, or exo-open, depending on which desktop you are using.

    I believe there is a project called xdg-utils that attempts to provide a unified interface to the local desktop.

    So, something like:

    snprintf(s, sizeof s, "%s %s", "xdg-open", the_file);
    system(s);
    

    Beware of code injection. It's safer to bypass scripting layers with user input, so consider something like:

    pid = fork();
    if (pid == 0) {
      execl("/usr/bin/xdg-open", "xdg-open", the_file, (char *)0);
      exit(1);
    }
    // parent will usually wait for child here
    

提交回复
热议问题