Using execlp system call with shell metacharacters in arguments in C
Program: List all C files in the current folder using a execlp()
system call:
#include <stdio.h>
#include <unistd.h>
int main()
{
printf("Before Execl\n");
execlp("ls","ls","*.c",NULL); // this should print all c files in the current folder.
return 0;
}
Program output:
Before Execl
ls: cannot access *.c: No such file or directory
Whenever I use ' *
' in the search pattern, I get a similar error. Please suggest a suitable solution.
source to share
If you want the shell metacharacters to be expanded, call the shell to expand them, like this:
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 returned functions exec*
failed. You don't need to check your status; it failed. Then you shouldn't be doing exit(0);
(or return 0;
in a function main()
) as this indicates success. It is polite to include an error message stating what went wrong and the message should be recorded in stderr
, not stdout
- as shown.
You can expand the metacharacter yourself; the POSIX library has functions to help (for example glob()
). But it's a whole bunch of easier ways to let the shell do it.
(I revisited the code above to use execlp()
to fit the requirements of the question. If I were to do this without restriction, I would probably use execl()
and specify "/bin/sh"
as the first argument instead.)
source to share