简体   繁体   中英

Execlp vs Execl

Is there any occasion in which is better to use execl instead of execlp ? I think that maybe when a program is in two different folders using execlp could lead to confusion but I don't know if it is the only case. I ask because one could think that writing execlp("ls", ...) is easier than writing execl("/bin/ls", ...) .

Security

Looking programs up via PATH is convenient, but it can also be insecure. If a directory in a user's PATH is world writable, it's possible to inject a malicious program into the PATH lookup. This would affect execlp but not execl .

For example, if you had a PATH like /foo/bar/bin:/home/you/bin:/usr/bin:/bin and /foo/bar/bin was world writable, someone with access to that machine could copy a malicious program to /foo/bar/bin/ls . Then executing ls would run /foo/bar/bin/ls rather than /bin/ls . They'd be able to execute commands as you and gain greater access.

For this reason, it's often a good idea to refer to specific executables in known locations. Or to hard wire a secure PATH in the executable.

Compatibility

While there is a common set of Unix commands and features specified by POSIX , many programs rely on extensions. If your program uses those extensions, grabbing the first one in the PATH might not be a good idea.

For example, here on OS X the installed utilities in /bin and /usr/bin are BSD-flavored. But I have GNU versions installed earlier in my PATH . A program designed to run on OS X would want to explicitly use, for example, /bin/ls or /usr/bin/tar to be sure they get a known version of those utilities.

$ /usr/bin/tar --version
bsdtar 2.8.3 - libarchive 2.8.3
$ tar --version
tar (GNU tar) 1.29

Both execl() and execlp() work fine and similarly if your executables are in different folders or in the same folder, but you need to set the $PATH if different folders.

execl() is needed for executing executables (like "ls") from command line as you can't go with execlp() in that case. I added a snapshot below.

#include<stdio.h>
#include<unistd.h>
int main(int argc, char *argv[])
{
        if(argc!=2)
        {
                printf("Usage Msg: ./a.out userdefined_executable \n");
                return;
        }
        //execl(argv[1],argv[1],NULL);//**it works** 
        execlp(argv[1],argv[1],NULL);//**it doesn't work** 
        return 0;
}

//Input will be like this, here "p1" is an user-defined executable.
//xyz@xyz:~/stack_overflow$ ./a.out p1 

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