对于Linux下的程序员来说,命令行参数是再常见不过的了,但是对于命令行参数的具体传递方式,我一直不是很明白,做了一个测试,代码如下:
- #include <stdio.h>
- #include <stdlib.h>
- /*
- * Author : Ahfyth
- */
- int main( int argc, char *argv[], char *env[] )
- {
- if( argc < 2 )
- {
- printf( "\nUsage : %s \n", argv[0] );
- printf( "\nThis program is designed to test the args.\n\n");
- return 1;
- }
- unsigned int i;
- for( i=0; i<argc; ++i )
- {
- printf( "Arg %d : %s\n", i, argv[i] );
- }
- if( argv[argc] == NULL )
- printf( "Arg %d == NULL : success.\n", argc );
- else
- printf( "Arg %d == NULL : fail.\n", argc );
- if( env == argv+argc+1 )
- printf( "env == argv+argc+1 : success.\n" );
- else
- printf( "env == argv+argc+1 : fail.\n" );
- i = 0;
- while( 1 )
- {
- if( env[i] == NULL )break;
- printf( "Env %d : %s\n", i, env[i] );
- ++ i;
- }
- return 0;
- }
输出结果如下:
./test a b c
(较长的行做了一些删减)
- Arg 0 : ./test
- Arg 1 : a
- Arg 2 : b
- Arg 3 : c
- Arg 4 == NULL : success.
- env == argv+argc+1 : success.
- Env 0 : BIOROLL=/opt/bio
- Env 1 : HOSTNAME=compute-0-11.local
- Env 2 : TERM=xterm
- Env 3 : SHELL=/bin/bash
- Env 4 : HISTSIZE=1000
- Env 5 : HMMER_DB=/home/ahfyth/bio/hmmer/db
- Env 6 : SSH_CLIENT=192.168.50.51 57413 22
- Env 7 : SGE_CELL=default
- Env 8 : SGE_ARCH=lx26-amd64
- Env 9 : MPICH_PROCESS_GROUP=no
- Env 10 : OLDPWD=/ifs-accel/ahfyth
- Env 11 : SSH_TTY=/dev/pts/0
- Env 12 : ANT_HOME=/opt/rocks
- Env 13 : USER=ahfyth
- Env 14 : LD_LIBRARY_PATH=/opt/gridengine/lib/lx26-amd64
- Env 15 : LS_COLORS=no=00:fi=00:di=00;34:ln=00;36:pi=40;33:
- Env 16 : ROCKS_ROOT=/opt/rocks
- Env 17 : MAIL=/var/spool/mail/sunkun
- Env 18 : PATH=/usr/java/latest/bin:/usr/local/bin:/bin:/usr/bin
- Env 19 : INPUTRC=/etc/inputrc
- Env 20 : PWD=/x200ifs-accel/program
- Env 21 : JAVA_HOME=/usr/java/latest
- Env 22 : SGE_EXECD_PORT=537
- Env 23 : LANG=en_US.iso885915
- Env 24 : SGE_QMASTER_PORT=536
- Env 25 : SGE_ROOT=/opt/gridengine
- Env 26 : BLASTDB=/home/ahfyth/bio/ncbi/db
- Env 27 : CS=/ifs-accel/program/Chip_seq/DownStream
- Env 28 : HISTCONTROL=ignoredups
- Env 29 : SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass
- Env 30 : SHLVL=1
- Env 31 : HOME=/home/sunkun
- Env 32 : PYTHONPATH=/ifs-accel/ahfyth/software
- Env 33 : LOGNAME=sunkun
- Env 34 : SSH_CONNECTION=192.168.50.51 57413 192.168.50.81 22
- Env 35 : LESSOPEN=|/usr/bin/lesspipe.sh %s
- Env 36 : BLASTMAT=/opt/bio/ncbi/data
- Env 37 : DISPLAY=localhost:10.0
- Env 38 : HISTTIMEFORMAT=%F %T
- Env 39 : G_BROKEN_FILENAMES=1
- Env 40 : _=./test
重点在第5行和第6行,也就是说命令行的参数argv和env是连接在一起的,中间只隔了一个NULL。
即使没有参数传进来,由于env一般较多(这里有40个),强制访问argv[10]一类的也是有值的!
阅读(1076) | 评论(0) | 转发(0) |