Home > Software engineering >  Why do programs with arguments passed in argc and argv get different results when executed in differ
Why do programs with arguments passed in argc and argv get different results when executed in differ

Time:10-21

void main(int argc,char *argv[])
{
     for (int i = 0; i < argc; i  )
     {
         printf("%s ", argv[i]);
     }
}

when I use command ./test 1 2 3 in terminal to execute this program, I got result ./test 1 2 3 ,but when I use function execl("/usr/src/test", "1", "2", "3", NULL) in another program I got result 1 2 3,why?

CodePudding user response:

The syntax of execl() is:

int execl(const char *path, const char *arg0, ..., /*, (char *)0, */);

So you have

path = "/usr/src/test"
arg0 = "1"
arg1 = "2"
arg3 = "3"

The argN parameters are put into the argv array of the new process.

You have to repeat the path as arg0 to put that into argv[0].

execl("/usr/src/test", "/usr/src/test", "1", "2", "3", NULL)

This isn't done automatically because argv[0] isn't required to be the same as the program path, and there are some situations where it isn't (for instance, login shells are invoked by adding a - prefix in argv[0]).

CodePudding user response:

Check the documentation for exec() family of functions:

It is explained there as follows:

The const char *arg and subsequent ellipses in the execl(), execlp(), and execle() functions can be thought of as arg0, arg1, ..., argn. Together they describe a list of one or more pointers to null-terminated strings that represent the argument list available to the executed program. The first argument, by convention, should point to the filename associated with the file being executed. The list of arguments must be terminated by a null pointer, and, since these are variadic functions, this pointer must be cast (char *) NULL.

  • Related