If you want shell metacharacters expanded, invoke the shell to expand them, thus:
execlp("sh", "sh", "-c", "ls *.c", (char *)0);
fprintf(stderr, "Failed to exec /bin/sh (%d %s)\n", errno, strerror(errno));
exit(EXIT_FAILURE);
Note that if execl()
or any of the exec*
functions returned, it failed. You don't need to test its status; it failed. You should not then do exit(0);
(or return 0;
in the main()
function) as that indicates success. It is courteous to include an error message outlining what went wrong, and the message should be written to stderr
, not stdout
— as shown.
You can do the metacharacter expansion yourself; there are functions in the POSIX library to assist (such as glob()
). But it is a whole heap simpler to let the shell do it.
(I've revised the code above to use execlp()
to conform to the requirements of the question. If I were doing this unconstrained, I'd probably use execl()
and specify "/bin/sh"
as the first argument instead.)