Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Getting command line parameters outside argv passed to main




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.

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:


$ 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

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.

- Steve

Attachment: smime.p7s
Description: S/MIME cryptographic signature

 _______________________________________________
Do not post admin requests to the list. They will be ignored.
Darwin-dev mailing list      (email@hidden)
Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/darwin-dev/email@hidden

This email sent to email@hidden

References: 
 >Getting command line parameters outside argv passed to main (From: Shawn Erickson <email@hidden>)
 >Re: Getting command line parameters outside argv passed to main (From: Steve Checkoway <email@hidden>)



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.