CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

31
1 CS 201 Computer Systems Programming Chapter 2 “argc argv envp, system(), libs” Herbert G. Mayer, PSU CS Herbert G. Mayer, PSU CS Status 1/15/2013 Status 1/15/2013

description

Herbert G. Mayer, PSU CS Status 1/15/2013. CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”. argc argv envp. Syllabus. Definitions Samples of argc argv envp Possible argv[] Implementation? References s ystem() Sample Uses of system() - PowerPoint PPT Presentation

Transcript of CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

Page 1: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

1

CS 201Computer Systems Programming

Chapter 2“argc argv envp, system(), libs”

Herbert G. Mayer, PSU CSHerbert G. Mayer, PSU CSStatus 1/15/2013Status 1/15/2013

Page 2: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

2

argc argv envp

Page 3: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

3

Syllabus DefinitionsDefinitions

Samples of Samples of argc argv envpargc argv envp

Possible Possible argv[] argv[] Implementation?Implementation?

ReferencesReferences

system()system()

Sample Uses of Sample Uses of system()system()

Unix Commands & C LibrariesUnix Commands & C Libraries

Page 4: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

4

Definitions In C the In C the main() main() function returns an int type result; function returns an int type result;

the formal parameter list may be void, or else the formal parameter list may be void, or else contains the specification of command line contains the specification of command line parametersparameters

In C++ the In C++ the main()main() return type is return type is intint; the formal ; the formal parameter list must be specified as parameter list must be specified as voidvoid, or else , or else defines the command line parameter typesdefines the command line parameter types

These are traditionally named These are traditionally named argc, argvargc, argv, and , and envpenvp; on Apple platforms a fourth parameter can be ; on Apple platforms a fourth parameter can be specified, not surprisingly named “apple”specified, not surprisingly named “apple”

The names “argc” and argv” may be chosen freely The names “argc” and argv” may be chosen freely to be any, but “argc” and “argv” are tradition to be any, but “argc” and “argv” are tradition

Page 5: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

5

Definitions argcargc

Specified as int argc, is main()’s first formal parameter argc counts the number of command line arguments that

argv[] holds for this current program execution Includes the object program itself, hence must be >= 1

argvargv Specified as char ** argv, equivalently char * argv[] is 2nd formal parameter of main(); optional; if specified, the

first parameter argc must already be specified argv is pointer to list of actual const string arguments

envpenvp Specified as char ** envp, equivalently char * envp[], is 3rd formal and optional parameter of main() Holds environment variables as string constants, plus the

indicating title: PATH=

Page 6: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

6

Reverse-Print Command Line Args// output command line arguments// output command line arguments// but in reverse order// but in reverse orderint main( int argc, char * argv[] )int main( int argc, char * argv[] ){ // main{ // main printf( "%d command line arguments passed.\n",printf( "%d command line arguments passed.\n",

argc );argc ); while( --argc > 0 ) {while( --argc > 0 ) { printf( "argument %d = \"%s\"\n”,printf( "argument %d = \"%s\"\n”,

argc, argv[ argc ] );argc, argv[ argc ] ); } //end while} //end while} //end main} //end main

[args] a.out 3 r 55[args] a.out 3 r 554 command line arguments passed.4 command line arguments passed.argument 3 = "55"argument 3 = "55"argument 2 = "r"argument 2 = "r"argument 1 = "3"argument 1 = "3"

Page 7: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

7

Sample argc, argv

a.out 12 '.' "345" E "+" 0a.out 12 '.' "345" E "+" 0Number of command line arguments passed Number of command line arguments passed = 7= 7This includes program nameThis includes program nameargv[0] = a.outargv[0] = a.outargv[1] = 12argv[1] = 12argv[2] = .argv[2] = . -- without single quote ‘-- without single quote ‘argv[3] = 345argv[3] = 345 -- without double quote “-- without double quote “argv[4] = Eargv[4] = Eargv[5] = +argv[5] = + -- without double quote “-- without double quote “argv[6] = 0argv[6] = 0Note that all “ and ‘ pairs are stripped awayNote that all “ and ‘ pairs are stripped awayAll command args concatenated areAll command args concatenated are = "12.345E+0" = "12.345E+0"Looks like the floating point number Looks like the floating point number = 12.345= 12.345

Page 8: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

8

Possible argv[] Implementation?

How are actual parameters passed to How are actual parameters passed to main()main() ? ?

Which tool passes them from the command line to the Which tool passes them from the command line to the run-time-system?run-time-system?

Students think, design, discuss:Students think, design, discuss:

1.) Will on-the-fly creation of assembler source program 1.) Will on-the-fly creation of assembler source program help? Assumes an assembly step to create another *.ohelp? Assumes an assembly step to create another *.o

2.) Will manipulation of stack, heap, code help, before or 2.) Will manipulation of stack, heap, code help, before or while loading provide the actual parameters?while loading provide the actual parameters?

3.) Other possibilities?3.) Other possibilities?

Page 9: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

9

Possible argv[] Implementation?Your Unix shell executes the Your Unix shell executes the a.out a.out commandcommand

Let’s say: Let’s say: a.out 100000 “9/12/2012”a.out 100000 “9/12/2012”

The shell sees the command line, verifies that The shell sees the command line, verifies that a.outa.out exists and is executable, then loads, executes, continues exists and is executable, then loads, executes, continues after returnafter return

All work to provide command line parameters is All work to provide command line parameters is accomplished between shell command and executionaccomplished between shell command and execution

Note that Note that a.outa.out may not be modified from one run to may not be modified from one run to anotheranother

So, sometimes So, sometimes argc, argv, envp argc, argv, envp may be accessed may be accessed during execution, other times notduring execution, other times not

Page 10: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

10

Sample envpThe Unix shell command The Unix shell command man setenv man setenv explains:explains:

man setenv:man setenv:

NAMENAME

set, unset, setenv, unsetenv, export -shell built-in functions to set, unset, setenv, unsetenv, export -shell built-in functions to determine the characteristics for environmental variables of the determine the characteristics for environmental variables of the current shell and its descendentscurrent shell and its descendents

Current environment variables used in your Unix environment are Current environment variables used in your Unix environment are tracked and can be output for any of your processestracked and can be output for any of your processes

Similar to Similar to char * argv[], envpchar * argv[], envp is also a pointer to an array of 0 or is also a pointer to an array of 0 or more strings, followed by a null stringmore strings, followed by a null string

Each such string contains one of your process’ environment Each such string contains one of your process’ environment variablesvariables

Page 11: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

11

Sample envp Version 1#include <iostream.h> // for: cin, cout, endl etc.#include <iostream.h> // for: cin, cout, endl etc.

int main( int argc, char ** argv, char ** envp )int main( int argc, char ** argv, char ** envp ){ // main{ // main int count = 0;int count = 0; while( *envp ) {while( *envp ) { cout << "envp[" << ++count << "] = \""cout << "envp[" << ++count << "] = \""

<< *envp << '"' << endl;<< *envp << '"' << endl; ++envp;++envp; // or envp++ if you prefer// or envp++ if you prefer } //end while} //end while cout << "Number of environment variables tracked = “cout << "Number of environment variables tracked = “

<< count << endl;<< count << endl; exit( 0 );exit( 0 );} //end main} //end main

Page 12: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

12

Sample envp Version 2#include <iostream.h> // for: cin, cout, endl etc.#include <iostream.h> // for: cin, cout, endl etc.

int main( int argc, char ** argv, char * envp[] )int main( int argc, char ** argv, char * envp[] ){ // main{ // main int index = 0;int index = 0; while( envp[ index ] ) {while( envp[ index ] ) { cout << "envp[" << index << "] = \""cout << "envp[" << index << "] = \"" << envp[ index++ ] << ‘"’ << endl; << envp[ index++ ] << ‘"’ << endl; } //end while} //end while cout << "Number of environment variables tracked = “cout << "Number of environment variables tracked = “

<< index << endl;<< index << endl; exit( 0 );exit( 0 );} //end main} //end main

Page 13: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

13

Sample envpenvp[1] = "USER=herb"envp[1] = "USER=herb"

envp[2] = "LOGNAME=herb"envp[2] = "LOGNAME=herb"

envp[3] = "HOME=/u/herb"envp[3] = "HOME=/u/herb"

envp[4] = "envp[4] = "PATHPATH=.:/usr/lang:/bin/sun4:/usr/etc:/vol/local/rhost/sun4/bin:/usr/ucb:/=.:/usr/lang:/bin/sun4:/usr/etc:/vol/local/rhost/sun4/bin:/usr/ucb:/bin:/vol/local:/vol/local/bin:/vol/local/sun4/bin:/usr/ccs/bin:/usr/ccs:/vol/bin:/vol/local:/vol/local/bin:/vol/local/sun4/bin:/usr/ccs/bin:/usr/ccs:/vol/userlocal/bin:/usr/local/bin:/home/vads/VADS_location/bin"userlocal/bin:/usr/local/bin:/home/vads/VADS_location/bin"

envp[5] = "MAIL=/var/mail//herb"envp[5] = "MAIL=/var/mail//herb"

envp[6] = "SHELL=/bin/csh"envp[6] = "SHELL=/bin/csh"

envp[7] = "TZ=US/Pacific"envp[7] = "TZ=US/Pacific"

. . . Many more. . . Many more

envp[12] = "LC_MONETARY=en_US.ISO8859-1"envp[12] = "LC_MONETARY=en_US.ISO8859-1"

envp[13] = "LC_MESSAGES=C"envp[13] = "LC_MESSAGES=C"

envp[14] = "LANG=en_US.UTF-8"envp[14] = "LANG=en_US.UTF-8"

envp[15] = "SSH_CLIENT=50.53.47.189 50625 22"envp[15] = "SSH_CLIENT=50.53.47.189 50625 22"

envp[16] = "SSH_CONNECTION=50.53.47.189 50625 131.252.208.127 22"envp[16] = "SSH_CONNECTION=50.53.47.189 50625 131.252.208.127 22"

envp[17] = "SSH_TTY=/dev/pts/33"envp[17] = "SSH_TTY=/dev/pts/33"

envp[18] = "TERM=xterm-256color"envp[18] = "TERM=xterm-256color"

envp[19] = "PWD=/u/herb/progs/args"envp[19] = "PWD=/u/herb/progs/args"

envp[20] = "term=vt100=”envp[20] = "term=vt100=”

Number of environment variables tracked = 20Number of environment variables tracked = 20

Page 14: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

14

References

1.1. http://crasseux.com/books/ctutorial/argc-and-argv.htmlhttp://crasseux.com/books/ctutorial/argc-and-argv.html

2.2. http://en.wikipedia.org/wiki/Main_function http://en.wikipedia.org/wiki/Main_function

3.3. http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Frefindex.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fmainf.htm%2Fmainf.htm

Page 15: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

15

system()

Page 16: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

16

system( “string” ) The The system()system() function is a C/C++ function, NOT a function is a C/C++ function, NOT a

shell command; causes error as a shell commandshell command; causes error as a shell command

Available in library Available in library #include <stdlib.h>#include <stdlib.h>

Passes its sole string parameter to the shell, as if Passes its sole string parameter to the shell, as if that same string had been typed as a shell that same string had been typed as a shell commandcommand

Exit status of last completed command is passed Exit status of last completed command is passed back to the shellback to the shell

If a null string is given, system( “” ) checks if the If a null string is given, system( “” ) checks if the shell exists and then terminatesshell exists and then terminates

Page 17: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

17

system( “string” ) Executed command returns with exit status in Executed command returns with exit status in

waitpid(3)waitpid(3) format, which is passed to invoking C format, which is passed to invoking C or C++ programor C++ program

waitpid()waitpid() reqires: reqires: #include <sys/types.h> #include <sys/types.h> and and #include <sys/wait.h>#include <sys/wait.h>

waitpid waitpid suspends execution of calling program suspends execution of calling program until status of terminated child process is available until status of terminated child process is available --any of its child processes--any of its child processes

Page 18: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

18

Sample Uses of system()

#include <stdlib.h>#include <stdlib.h>

int main()int main(){ // main{ // main system( "man system" );system( "man system" );} //end main} //end main

Write C++ program, using Write C++ program, using system()system() that prints the that prints the Unix man page for Unix man page for system()system()

Just as if command “man system” had been spelled Just as if command “man system” had been spelled as a Unix shell commandas a Unix shell command

Sample shown below:Sample shown below:

Page 19: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

19

Sample Uses of system()

#include <stdlib.h>#include <stdlib.h>int main( void )int main( void ){ // main{ // main system( "cd ..; ls -la; cd arg_test; ls -la" );system( "cd ..; ls -la; cd arg_test; ls -la" );} //end main} //end main

Write C++ program using Write C++ program using system() system() that:that: Changes directory from . named arg_test, to one level up .. Then lists all files in that .. directory via: ls –la Changes back to directory arg_test And finally shows all files listed in that directory arg_test

Sample below:Sample below:

Page 20: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

20

Sample Uses of system()

#include <stdlib.h>#include <stdlib.h>#include <iostream.h>#include <iostream.h>#define command "pwd”#define command "pwd”int main( int argc, char * argv[] )int main( int argc, char * argv[] ){ // main{ // main cout << "using string const 'pwd'" << endl;cout << "using string const 'pwd'" << endl; system( command );system( command ); cout << "using argv[ 1 ]" << endl;cout << "using argv[ 1 ]" << endl; system( argv[ 1 ] );system( argv[ 1 ] );} //end main} //end main

Write C++ program using Write C++ program using system()system() that prints the that prints the current working directory, by specifying the const current working directory, by specifying the const string literal string literal “pwd”“pwd”

And by passing in the command through And by passing in the command through argv[]argv[] Sample shown below:Sample shown below:

Page 21: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

21

Tricky Sample Use system()

#include <stdlib.h>#include <stdlib.h>#include <iostream.h>#include <iostream.h>#include <time.h>#include <time.h>// file name: sys7.cpp// file name: sys7.cppint main( void )int main( void ){ // main{ // main time_t cur_time = time( '\0' );time_t cur_time = time( '\0' );

// mix C and C++ I/O// mix C and C++ I/O printf( "%s", asctime( localtime( & cur_time ) ) );printf( "%s", asctime( localtime( & cur_time ) ) ); cout << "After being modified" << endl;cout << "After being modified" << endl; system( "g++ -Wno-deprecated sys7.cpp; system( "g++ -Wno-deprecated sys7.cpp; a.outa.out" );" ); cout << "We’ll never get here cout << "We’ll never get here " << endl;" << endl;} //end main} //end main

Write C++ program using Write C++ program using system()system() prints the prints the current date/timecurrent date/time

Then compiles and runs its own source Then compiles and runs its own source sys7.cppsys7.cpp Watch out what happens with C++ file Watch out what happens with C++ file sys7.cppsys7.cpp::

Page 22: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

22

Unix Commands & C Libraries

Page 23: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

23

Unix Commands, C++ Libraries C and C++ are mature languages, widely used, yet C and C++ are mature languages, widely used, yet

offering limited high-level language facilitiesoffering limited high-level language facilities No array assignments No lexically nested functions or procedures Limited built-in functions, hence the numerous libraries

Libraries render C/C++ language rich and versatile Libraries render C/C++ language rich and versatile in use; some Unix libs, commands are ubiquitous, in use; some Unix libs, commands are ubiquitous, e.g.:e.g.:1. ps command2. setenv command3. signal.h lib4. stdlib.h lib5. sys/types.h lib6. time.h command and lib

Page 24: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

24

Unix Command ps Name:Name: psps Purpose:Purpose: print status of current processesprint status of current processes Functions:Functions: prints information about active prints information about active

processes. Without options, lists processes with processes. Without options, lists processes with same effective user ID and controlling terminal as same effective user ID and controlling terminal as invokerinvoker

Output contains process ID, terminal ID, cumulative Output contains process ID, terminal ID, cumulative execution time, and command nameexecution time, and command name

Options are numerous: Options are numerous: ps [-aAcdefjlLPyZ] [-g ps [-aAcdefjlLPyZ] [-g grplist] [-n namelist] [-o format] [-p grplist] [-n namelist] [-o format] [-p proclist] [-s sidlist] [-t term] [-u proclist] [-s sidlist] [-t term] [-u uidlist] [-U uidlist] [-G gidlist] [-z uidlist] [-U uidlist] [-G gidlist] [-z zonelist]zonelist]

Page 25: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

25

Unix Command setenv

USER=herbUSER=herbLOGNAME=herbLOGNAME=herbHOME=/u/herbHOME=/u/herbPATH=.:/usr/lang:/bin ... long list of pathsPATH=.:/usr/lang:/bin ... long list of pathsMAIL=/var/mail//herbMAIL=/var/mail//herbSHELL=/bin/cshSHELL=/bin/cshTZ=US/PacificTZ=US/PacificLC_CTYPE=en_US.ISO8859-1LC_CTYPE=en_US.ISO8859-1LC_COLLATE=en_US.ISO8859-1 ... etc.LC_COLLATE=en_US.ISO8859-1 ... etc.

Name:Name: setenvsetenv Purpose:Purpose: reports of environment variables for reports of environment variables for

the current process and all its descendentsthe current process and all its descendents Function:Function: various commands are various commands are set unset set unset

unsetenv exportunsetenv export Sample Use without arguments:Sample Use without arguments:

Page 26: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

26

$PATH, etc. on PSU’s Odin, Sirius On Unix shell, issue the command On Unix shell, issue the command man shell_builtins man shell_builtins and learn and learn

about several interesting commands, e.g.:about several interesting commands, e.g.: alias echo $PATH setenv

Command Command echo $PATH echo $PATH shows the one line your program did output –shows the one line your program did output –plus many more– when scanning through plus many more– when scanning through envp[]envp[]

That was the line starting with That was the line starting with PATH=./user/ . . .PATH=./user/ . . . Or just issue command Or just issue command $PATH $PATH and observe the error at endand observe the error at end Again you will see a path for all directories searched, in order, to Again you will see a path for all directories searched, in order, to

resolve a command --or finding a file-- you specifiedresolve a command --or finding a file-- you specified Command Command setenvsetenv without arguments will provide information that your without arguments will provide information that your

program outputs, when scanning through program outputs, when scanning through envp[]envp[] What if you wish to add directory What if you wish to add directory /u/herb/progs/u/herb/progs to your search path to your search path

$PATH$PATH?? Issue command Issue command setenv PATH $PATH\:/u/herb/progssetenv PATH $PATH\:/u/herb/progs, , will add will add

/u/herb/progs/u/herb/progs at the end of existing pathat the end of existing path

Page 27: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

27

C Library signal Name:Name: #include <signal.h>#include <signal.h> Purpose:Purpose: provide signal management for provide signal management for

application processesapplication processes Key Functions with 1Key Functions with 1stst argument sig: argument sig: signal() signal()

sigset() sighold() sigrelse() sigignore() sigset() sighold() sigrelse() sigignore() sigpause()sigpause()

SignalsSignals are tools for asynchronous interprocess are tools for asynchronous interprocess communication in Unix. Signal is sent to process or communication in Unix. Signal is sent to process or thread of the same process to notify that a specific thread of the same process to notify that a specific event (the signal) has occurred. Some of the event (the signal) has occurred. Some of the functions set, others remove etc. the event functions set, others remove etc. the event recording. If process has registered a signal recording. If process has registered a signal handler, that handler is executed upon signal sethandler, that handler is executed upon signal set

Page 28: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

28

C Library stdlib Name:Name: #include <stdlib.h>#include <stdlib.h> Purpose:Purpose: defines key functions and macrosdefines key functions and macros Key Functions: Key Functions: exit() malloc() printf() ... exit() malloc() printf() ...

Page 29: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

29

C Library types Name:Name: #include <sys/types.h>#include <sys/types.h> Purpose:Purpose: defines 100s of types for 32-bit and 64-defines 100s of types for 32-bit and 64-

bit target systemsbit target systems Key Functions:Key Functions:

clock_tclock_t

time_ttime_t

pid_tpid_t

size_tsize_t

_CHAR_IS_SIGNED (or UNSIGNED)_CHAR_IS_SIGNED (or UNSIGNED)

Page 30: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

30

C Library time

time_t cur_time = time( '\0' ); time_t cur_time = time( '\0' ); printf( "%s", asctime( localtime( & cur_time ) ) );printf( "%s", asctime( localtime( & cur_time ) ) );

Name:Name: #include <time.h>#include <time.h> Purpose:Purpose: tracking run-timetracking run-time Key Functions:Key Functions:

localtime()localtime() returns: returns: struct tm*struct tm*

single argument: single argument: const * clockconst * clock

asctime()asctime() returns: returns: char *char *

single argument: single argument: const struct tm*const struct tm*

Page 31: CS 201 Computer Systems Programming Chapter 2 “ argc argv envp, system(), libs ”

31

Unix Command time

time a.outtime a.out41.0u 1.0s 0:42 98% 0+0k 0+0io 0pf+0w41.0u 1.0s 0:42 98% 0+0k 0+0io 0pf+0w

Command name:Command name: timetime Purpose:Purpose: measures time of command executionmeasures time of command execution Functions:Functions: outputs time to standard error, as:outputs time to standard error, as:

real time, ie. wall-clock, in float formatreal time, ie. wall-clock, in float format

user time, in float formatuser time, in float format

system time, in float formatsystem time, in float format