Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does execve know how many arguments are passed in argv?

Tags:

execve

In C programs, the main function knows how many arguments are passed to in argv by looking at argc. It seems unclear to me how the syscall execve knows how many arguments are passed to it. Could someone help explain how execve handles the arguments?

like image 271
rchen Avatar asked Oct 21 '25 20:10

rchen


1 Answers

The documentation for execve on my nearest Linux system says:

argv is an array of argument strings passed to the new program. envp is an array of strings, conventionally of the form key=value, which are passed as environment to the new program. Both argv and envp must be terminated by a null pointer. The argument vector and environment can be accessed by the called program’s main function, when it is defined as:

int main(int argc, char *argv[], char *envp[])

I have bolded the important part. There must be a null pointer at the end of the argv list. The kernel will count the arguments and pass the count as argc.

like image 154
Greg Hewgill Avatar answered Oct 24 '25 10:10

Greg Hewgill