Re: Getting command line parameters outside argv passed to main
site_archiver@lists.apple.com Delivered-To: darwin-dev@lists.apple.com On Dec 19, 2005, at 12:38 PM, Steve Checkoway wrote: On Dec 19, 2005, at 12:15 PM, Shawn Erickson wrote: If no built-in feature exists I will simply grab the arguments while in main and stash what I need in a global var for later use or accessible via some internal api. That's what I always do. $ cat args2.c #include <stdio.h> extern char **environ; extern char **NXArgv; extern int NXArgc; static void print_args( int real_path ) { char **envp = environ; char **argv = NXArgv; while( *(envp++) ) ; fputs( real_path ? *envp : *argv, stdout ); while( *(++argv) ) printf( " %s", *argv ); puts( "" ); } int main() { print_args( 0 ); print_args( 1 ); return 0; } $ gcc -Wall args2.c $ ./a.out foo bar baz ./a.out foo bar baz ./a.out foo bar baz e$ cat bad.c #include <unistd.h> int main( int argc, char **argv, char **envp ) { char *new_argv[] = { "lying", "foo", "bar", "baz", NULL }; execve( "./a.out", new_argv, envp ); _exit(1); } $ gcc -Wall -o bad bad.c $ ./bad lying foo bar baz ./a.out foo bar baz - Steve _______________________________________________ Do not post admin requests to the list. They will be ignored. Darwin-dev mailing list (Darwin-dev@lists.apple.com) Help/Unsubscribe/Update your Subscription: http://lists.apple.com/mailman/options/darwin-dev/site_archiver%40lists.appl... This email sent to site_archiver@lists.apple.com I suppose it might be possible to walk backward from environ to get the command line parameters: Actually, it's even easier than that. For something totally unrelated, I was reading some of darwin's source and I noticed NXArgc and NXArgv as well as something else that's interesting: Argv[0] doesn't have to be the same thing that's passed to execve as bad.c shows. However, either start() or _start() [I forget which] puts the actual path just after the NULL that follows the environment. smime.p7s
participants (1)
-
Steve Checkoway