简体   繁体   中英

Using execlp system call with shell metacharacters in the arguments in C

Program : List all C files in the current folder using 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 am getting a similar kind of error. Please suggest some appropriate solution.

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.)

Exec does not handle the " * " operator as the shell does it for you. Use popen() or glob_t for this. You can get more details on a similar question which I asked on 2012-03-08.

应该是:

   execlp("ls", "*.c", NULL);
execlp("ls", "*.c", NULL);

应该管用

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM