Alex Rivera | Logout

Why first arg to execve() must be path to executable

Asked 2010-06-12T03:08:28.227
9

I understand that execve() and family require the first argument of its argument array to be the same as the executable that is also pointed to by its first argument. That is, in this:

execve(prog, args, env);

args[0] will usually be the same as prog. But I can't seem to find information as to why this is.

I also understand that executables (er, at least shell scripts) always have their calling path as the first argument when running, but I would think that the shell would do the work to put it there, and execve() would just call the executable using the path given in its first argument ("prog" from above), then passing the argument array ("args" from above) as one would on the command line.... i.e., I don't call scripts on the command line with a duplicate executable path in the args list....

/bin/ls /bin/ls /home/john

Can someone explain?

Edit
Report

1 Answer

8

According to this, the first argument being the program name is a custom.

by custom, the first element should be the name of the executed program (for example, the last component of path)

That said, these values could be different. If for example, the program was launched from a symbolic link. The program name might be different than that of the link used to launch it.

And, you are right. The shell would normally do the work of setting up the first argument. In this case however, the use of execve circumvents the shell altogether - which is why you need to set it up yourself.

answered 2010-06-12T03:19:49.100

Your Answer