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 11/19/2012 Status 11/19/2012

Upload: flynn-bridges

Post on 03-Jan-2016

23 views

Category:

Documents


0 download

DESCRIPTION

Herbert G. Mayer, PSU CS Status 11/19/2012. 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

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 11/19/2012Status 11/19/2012

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 function returns an int type

result; the formal parameter list may be void, result; the formal parameter list may be void, or contain the specification of command line or contain 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 , or else must define the command line parameter else must define the command line parameter typestypes

These are traditionally named These are traditionally named argc, argvargc, argv, and , and envpenvp; on Apple platforms a fourth parameter can ; on Apple platforms a fourth parameter can be specified, not surprisingly named “apple”be 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, this is main()’s first formal parameter, and of type int

argc counts number of command line argv[] given for this current run of an object program

Includes the object program itself, hence must be >= 1

argvargv Specified as char ** argv or equivalently char *

argv[], is 2nd formal parameter of main() argv is list of actual arguments, each of type

const string

envpenvp Specified as char ** envp or equivalently char *

envp[], and is 3rd formal parameter of main() Holds environment variable names as string

constants

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

6

Sample Reverse-Print Parameters// 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

Samples argc, argvFor example, if you compile C++ program For example, if you compile C++ program chess.cppchess.cpp with option with option Wno-deprecatedWno-deprecated, rename , rename a.outa.out to to chess.ochess.o, then issue the command: , then issue the command: chess.o board.txt Masterchess.o board.txt Master

argcargc == 33

argv[0]argv[0] == chess.ochess.o

argv[1]argv[1] == board.txtboard.txt

aargv[2]rgv[2] == MasterMaster

argv[3]argv[3] == null pointer, provided to null pointer, provided to mark “end”mark “end”

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

8

Samples argc, argva.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] = .argv[3] = 345argv[3] = 345argv[4] = Eargv[4] = Eargv[5] = +argv[5] = +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 floating point number Looks like floating point number = 12.345= 12.345

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

9

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 Which tool passes them from the command line to the run-time-system?the run-time-system?

Students think, design, discuss:Students think, design, discuss:1.) Will on-the-fly creation of assembler source 1.) Will on-the-fly creation of assembler source program help? Assumes an assembly step to create program help? Assumes an assembly step to create another *.oanother *.o

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

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

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

10

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

Let’s say the command is: Let’s say the command is: a.out 100000 a.out 100000 “9/12/2012”“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, exists and is executable, then loads, executes, continues after returnexecutes, continues after return

All work to provide command line parameters is All work to provide command line parameters is accomplished in between shell command and start accomplished in between shell command and start of execof exec

Note that Note that a.outa.out may not be modified may not be modified

Moreover, sometimes Moreover, sometimes argc, argv, envp argc, argv, envp may be may be accessed during execution, at other times they accessed during execution, at other times they are inaccessibleare inaccessible

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

11

Samples 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 current determine the characteristics for environmental variables of the current shell and its descendentsshell and its descendents

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

Similar to Similar to char * argv[], envpchar * argv[], envp is also a pointer to an is also a pointer to an array of strings, the last one of which is followed by a array of strings, the last one of which is followed by a null stringnull string

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

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

12

Samples envp#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++; } //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 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-http://crasseux.com/books/ctutorial/argc-and-argv.htmlargv.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/http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%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, function is a C/C++ function,

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

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

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

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

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

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

17

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

in in waitpid(3)waitpid(3) format, which is passed to format, which is passed to invoking C or C++ programinvoking C or 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 suspends execution of calling program until status of terminated child program until status of terminated child process is available --any of its child process is available --any of its child processesprocesses

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 that prints the Unix man page for prints the Unix man page for system()system()

Just as if command “man system” had been Just as if command “man system” had been spelled as a Unix shell commandspelled as 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 that prints the current working directory, by prints the current working directory, by specifying the const string literal specifying the const 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>int 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; a.out" );system( "g++ -Wno-deprecated sys7.cpp; a.out" );} //end main} //end main

Write C++ program using Write C++ program using system()system() prints prints the current date/timethe current 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 C and C++ are mature languages, widely

used, yet offering limited high-level used, yet offering limited high-level language facilitieslanguage 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 Libraries render C/C++ language rich and

versatile in use; some Unix libs, versatile in use; some Unix libs, commands are ubiquitous, e.g.:commands are ubiquitous, 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 print status of current

processesprocesses Functions:Functions: prints information about prints information about

active processes. Without options, lists active processes. Without options, lists processes with same effective user ID and processes with same effective user ID and controlling terminal as invokercontrolling terminal as invoker

Output contains process ID, terminal ID, Output contains process ID, terminal ID, cumulative execution time, and command cumulative execution time, and command namename

Options are numerous: Options are numerous: ps [-aAcdefjlLPyZ] ps [-aAcdefjlLPyZ] [-g grplist] [-n namelist] [-o format] [-[-g grplist] [-n namelist] [-o format] [-p proclist] [-s sidlist] [-t term] [-u p 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 ... ong list of pathsPATH=.:/usr/lang:/bin ... ong 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 reports of environment

variables for the current process and all variables for the current process and all its descendentsits 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 shows the one lecho $PATH shows the one line your program did output ine 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 Again you will see a path for all directories searched, in

order, to resolve a command --or finding a file-- you order, to resolve a command --or finding a file-- you specifiedspecified

Command Command setenv setenv without arguments will provide the same without arguments will provide the same information your program output, when scanning through information your program output, 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 to your search path search path $PATH$PATH??

Issue command Issue command setenv PATH $PATH\:/u/herb/progs, setenv PATH $PATH\:/u/herb/progs, will add will add /u/herb/progs/u/herb/progs at the end of existing path at 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() sigset() sighold() sigrelse() signal() sigset() sighold() sigrelse() sigignore() sigpause()sigignore() sigpause()

SignalsSignals are tools for asynchronous are tools for asynchronous interprocess communication in Unix. interprocess communication in Unix. Signal is sent to process or thread of Signal is sent to process or thread of the same process to notify that a the same process to notify that a specific event (the signal) has occurred. specific event (the signal) has occurred. Some of the functions set, others remove Some of the functions set, others remove etc. the event recording. If process has etc. the event recording. If process has registered a signal handler, that handler registered a signal handler, that handler is executed upon signal setis 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 defines key functions and

macrosmacros Key Functions: Key Functions: exit() malloc() exit() malloc()

printf() ... 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-defines 100s of types for 32-

bit and 64-bit target systemsbit and 64-bit 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 const struct tm*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 measures time of command

executionexecution Functions:Functions: outputs time to standard outputs time to standard

error, as:error, as:

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

user time, in float formatuser time, in float format

system time, in float formatsystem time, in float format