Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do programs with arguments passed in argc and argv get different results when executed in different ways

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading