I expected one cannot fork if the application is not installed
As per documentation, popen
starts the shell (using /bin/sh -c
on POSIX systems), and returns you a file descriptor connected to the shell output (or input, depending on the second parameter). The validity of the command is irrelevant to the success of popen
"per se", so you are not going to get NULL
in output (which is to be expected for lower-level failures, such as impossibility to fork, to create file descriptors or to exec
the shell itself, all stuff that "shouldn't happen" unless in low-resources situations).
You'll just get whatever message the shell will spit out on standard output (probably none, as it will be on standard error); incidentally, this is one of the reasons why generally popen
is not a good idea if you need decent diagnostics of what went wrong.
What you can do, however, is to inspect the return code of pclose
, which will provide you the shell exit code, that you may use to find out some details about what went wrong (if any).
That being said, "launching" a file according to the user preferences is generally best delegated to the operating system or to OS-supplied utilities; easy ways to do so are the ShellExecute
API on Windows, the open
utility on macOS, and the xdg-open
utility on most Linux installations1.
As for getting the executable to be used to start a file, it's a way more complicated matter. I don't know about macOS, but on Windows a file may be associated to something more complicated than a "plain" executable (possibly with a command line) - there used to be DDE commands, some new fancy MSI abominations that auto-install stuff on demand and other "magic" shell stuff; I suspect that even on Linux there will be some broken support for DBus activation of applications and stuff like that; so, in general there's no such a thing as an "associated executable", just ask the system to open the file and stay out of this kind of trouble.
- As always happens, Linux "desktop" stuff is way more fragmented, complicated and unreliable than it needs to be, but
xdg-open
is generally a safe-ish bet (although I saw it fail as well). Don't go down Firefox's path of trying to do this stuff on its own, or you too will have 10 years old bugs on wrong applications being started that periodically resurface.