The "classical" way of invoking a program from an existing process on any of the UNIX-like OS'es is to use one of the exec()
functions. When you read about exec()
most tutorials will start by explaining another function: fork()
. These functions are very commonly used together, but don't get too caught up on that, because they are both useful in their own right.
To answer your question, a fairly efficient way of doing what you're after:
- Take the user generated input from whatever your source happens to be
- (Optionally, call
fork()
)
- Call the
execvp()
function
- What you do here will depend on whether you called
fork()
in step (2), and what you intend to do (if anything) after performing the task you described.
execvp() will do the legwork for you, by automatically searching on your environment PATH for a filename matching the first argument. If the current environment does not have a PATH set, it will default to /bin:/usr/bin
. Since the only way that a call to exec()
can yield a return value is when that call failed, you might want to check the value of errno
as part of step (4). In the event that the user input didn't match any executable in the environment PATH, errno
will be set to ENOENT
. Exactly how you do this and what additional steps might be worth taking will depend on whether or not you forked, along with any additional requirements for your program.