I’m using popen to run a system script, like so:
snprintf(cmd, MAX_PATH, "/myscript -q | grep -i %s", deviceName);
FILE *res = popen(cmd, "r");
If the script is not found, the program carries on its merry way. However, a “file or directory not found” message is displayed, which seems like an error even though in my intended usage it isn’t.
Is there a way to silence this message, or should I just call ls | grep -i myscript before running this line?
Assuming your
/bin/shis a POSIX shell, or a reasonably recent Bourne shell variant, you can redirect standard output within the command before executing the actual command. You only need to prependexec 2>/dev/null ;before the command you wish to execute.Here is how I’d personally do this:
The
popen()command uses/bin/shinternally to run the specified command. The above works for all/bin/shvariants I can test, including Linux and SunOS 5.10, so it should be quite portable. (In other words,dash,bash, and SunOS 5.10shall work fine with it.)Since you’ll need to recompile the application for any nonstandard systems, you can always edit the macro to omit the prefix. (You can easily add a test to
Makefilemagic to automatically omit it if necessary, if you ever find such a system.)Note that I modified the parameter substitution in the
snprintf()call. It will work for anydeviceNamethat does not contain a single quote. Any single quotes indeviceNameshould be replaced with the string'"'"'before thesnprintf()call.Questions?