cs 201 computer systems programming chapter 2 argc, argv, envp, system(), libs

39
1 CS 201 Computer Systems Programming Chapter 2 argc, argv, envp, system(), libs Herbert G. Mayer, PSU CS Herbert G. Mayer, PSU CS Status 6/13/2014 Status 6/13/2014

Upload: annora

Post on 19-Jan-2016

24 views

Category:

Documents


0 download

DESCRIPTION

Herbert G. Mayer, PSU CS Status 6/13/2014. 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? Sample envp Concatenate References 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 2argc, argv, envp, system(), libs

Herbert G. Mayer, PSU CSHerbert G. Mayer, PSU CSStatus 6/13/2014Status 6/13/2014

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?

Sample Sample envpenvp

ConcatenateConcatenate

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 function returns an intint result; the result; the

formal parameter list may be empty, or else contain formal parameter list may be empty, or else contain the specification of command line parametersthe specification of command line parameters

In C++, the In C++, the main()main() function also returns an function also returns an intint type result; yet the formal parameter list must be type result; yet the formal parameter list must be specified as specified as voidvoid in C++, if in C++, if main()main() does not does not specify command line parametersspecify command line parameters

These are traditionally named These are traditionally named argcargc, , argvargv, and , and envpenvp; on Apple platforms a fourth parameter can be ; on Apple platforms a fourth parameter can be specified, not surprisingly named “specified, not surprisingly named “appleapple””

Environment variable Environment variable names names may be chosen freely, may be chosen freely, but “argc” and “argv” are tradition but “argc” and “argv” are tradition

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

5

Definitions

int main( int main(

int int argcargc,, // specifies # in argv[]// specifies # in argv[]

char * argv[],char * argv[], // list of parameters// list of parameters

char * envp[] )char * envp[] ) // all environment vars// all environment vars

{ // main{ // main

. . .. . .

} //end main} //end main

•Why specify Why specify argcargc??

•To allow empty-string command line parametersTo allow empty-string command line parameters

•Cannot have a null environment variableCannot have a null environment variable

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

6

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 a pointer to the 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

header: PATH=

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

7

C Quirks Note that for Note that for argv[]argv[] an ancillary data structure is an ancillary data structure is

provided: provided: argcargc

Thus it is possible to pass an empty string as Thus it is possible to pass an empty string as one/some of the various command line argumentsone/some of the various command line arguments

And if your program scans for the “end of the list” by checking for the null string, your loop terminates checking the argv[] values too early; hence argc

This is not possible with This is not possible with envp[]envp[], as no empty (null , as no empty (null string) environment variable can be specifiedstring) environment variable can be specified

Delicate point, but that is what Delicate point, but that is what system programming system programming is all about!is all about!

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

8

Reverse-Print Command Line Args// output all command line arguments of a.out:// output all command line arguments of a.out:// but in reverse order of command line// but in reverse order of command lineint main( int argc, char * argv[] ) // ignore envpint main( int argc, char * argv[] ) // ignore envp{ // main{ // main printf( "%d command line args passed.\n", argc );printf( "%d command line args passed.\n", argc ); while( --argc > 0 ) { // pre-decrement skips a.outwhile( --argc > 0 ) { // pre-decrement skips a.out printf( "arg %d = \"%s\"\n", argc, argv[ argc ] );printf( "arg %d = \"%s\"\n", argc, argv[ argc ] ); } //end while} //end while} //end main} //end main

[args] a.out 3 r 55 [args] a.out 3 r 55 the command line entered the command line entered4 command line args passed.4 command line args passed.arg 3 = "55"arg 3 = "55"arg 2 = "r"arg 2 = "r"arg 1 = "3"arg 1 = "3"

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

9

Sample 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] = . -- 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 matching “ and ‘ pairs on command line are Note that all matching “ and ‘ pairs on command line are stripped away; all command args concatenated arestripped away; all command args concatenated are "12.345E+0”; l"12.345E+0”; looks like float numberooks like float number 12.345 12.345

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

10

Possible argv[] Implementation?

How are such actual parameters passed to How are such 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? Discuss or email good ideas, and 3.) Other possibilities? Discuss or email good ideas, and get extra credit!get extra credit!

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

11

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 The shellshell sees the command line, verifies that sees the command line, verifies that a.outa.out exists and is executable, loads your program, does ?? exists and is executable, loads your program, does ?? magic, executes your program, continues after exitmagic, executes your program, continues after exit

At the point of At the point of ???? some some magic magic happenshappens

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

Clearly Clearly a.outa.out may not be modified from run to runmay not be modified from run to run

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

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

12

Sample envpThe Unix shell command The Unix shell command man setenv man setenv generates this output:generates this output:

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 descendents . . Much morecurrent shell and its descendents . . Much more

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[], char * argv[], envpenvp 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 13: CS 201 Computer Systems  Programming Chapter  2 argc, argv, envp, system(), libs

13

Sample envp Version in C

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 ] ) { // OK to assume null-terminated stringswhile( envp[ index ] ) { // OK to assume null-terminated strings

// print one environment variable at a time// print one environment variable at a time

printf( "printf( "envp[%d] = envp[%d] = \"%s\"\n", index, envp[ index++ ] );\"%s\"\n", index, envp[ index++ ] );

} //end while} //end while

printf( "Number of environment vars = %d\n", index );printf( "Number of environment vars = %d\n", index );

exit( 0 );exit( 0 );

} //end main} //end main

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

14

Sample envp, Counting from 1environment variable 1 environment variable 1 = "USER=herb"= "USER=herb"

environment variable 2 = "LOGNAME=herb"environment variable 2 = "LOGNAME=herb"

environment variable 3 = "HOME=/u/herb"environment variable 3 = "HOME=/u/herb"

environment variable 4 = environment variable 4 = ""PATHPATH=.:/usr/lang:/bin/sun4:/usr/etc:/vol/local/rhost/sun4/bin:/usr/ucb:/bin:/vol/local:/=.:/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/userlocal/bin:/usr/local/vol/local/bin:/vol/local/sun4/bin:/usr/ccs/bin:/usr/ccs:/vol/userlocal/bin:/usr/local/bin:/home/vads/VADS_location/bin"bin:/home/vads/VADS_location/bin"

environment variable 5 = "MAIL=/var/mail//herb"environment variable 5 = "MAIL=/var/mail//herb"

environment variable 6 = "SHELL=/bin/csh"environment variable 6 = "SHELL=/bin/csh"

environment variable 7 = "TZ=US/Pacific"environment variable 7 = "TZ=US/Pacific"

. . . And many more. . . And many more

environment variable 12 = "LC_MONETARY=en_US.ISO8859-1"environment variable 12 = "LC_MONETARY=en_US.ISO8859-1"

environment variable 13 = "LC_MESSAGES=C"environment variable 13 = "LC_MESSAGES=C"

environment variable 14 = "LANG=en_US.UTF-8"environment variable 14 = "LANG=en_US.UTF-8"

environment variable 15 = "SSH_CLIENT=50.53.47.189 50625 22"environment variable 15 = "SSH_CLIENT=50.53.47.189 50625 22"

environment variable 16 = "SSH_CONNECTION=50.53.47.189 50625 131.252.208.127 22"environment variable 16 = "SSH_CONNECTION=50.53.47.189 50625 131.252.208.127 22"

environment variable 17 = "SSH_TTY=/dev/pts/33"environment variable 17 = "SSH_TTY=/dev/pts/33"

environment variable 18 = "TERM=xterm-256color"environment variable 18 = "TERM=xterm-256color"

environment variable 19 = "PWD=/u/herb/progs/args"environment variable 19 = "PWD=/u/herb/progs/args"

environment variable 20 = "term=vt100=”environment variable 20 = "term=vt100=”

Number of environment vars = 20Number of environment vars = 20

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

15

Concatenate

char char g_stringg_string[ 100000 ]; // large enough to hold command line arguments[ 100000 ]; // large enough to hold command line arguments

// return string pointing to concatenation of command line args, not 1st// return string pointing to concatenation of command line args, not 1st

char * cat_not_first( int argc, char * argv[] )char * cat_not_first( int argc, char * argv[] )

{ // cat_not_first{ // cat_not_first

g_string[ 0 ] = (char)(0); // place null into first characterg_string[ 0 ] = (char)(0); // place null into first character

for ( int i = 1; i < argc; i++ ) {for ( int i = 1; i < argc; i++ ) { // don’t start at 0, for “a.out”// don’t start at 0, for “a.out”

strcatstrcat( ( g_stringg_string, argv[ i ] );, argv[ i ] );

} //end for} //end for

return return g_stringg_string;;

} //end cat_not_first} //end cat_not_first

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

16

References

1.1. http://crasseux.com/books/ctutorial/argc-and-argv.html http://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 17: CS 201 Computer Systems  Programming Chapter  2 argc, argv, envp, system(), libs

17

system()

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

18

system( “string” )

The The system()system() function is a C function, NOT a shell function is a C function, NOT a shell command; causes error as a shell commandcommand; 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 via a shell that same string had been typed via a shell commandcommand

Exit status of last completed command is passed Exit status of last completed command is passed back to the invoking C programback to the invoking C program

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

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

19

system( “string” ) Completed (last) command returns with exit status Completed (last) command returns with exit status

in in waitpid(3)waitpid(3) format, which is passed to the format, which is passed to the invoking C programinvoking 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 20: CS 201 Computer Systems  Programming Chapter  2 argc, argv, envp, system(), libs

20

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 a C program, using Write a C program, using system()system() that prints the that prints the Unix Unix man page man page for for system()system()

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

Sample shown below:Sample shown below:

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

21

Sample Uses of system()

#include <stdlib.h>#include <stdlib.h>int main( void )int main( void ){ // main{ // main

// assume execution in directory arg_test// assume execution in directory arg_test system( "cd ..; ls -la; cd arg_test; ls -la" );system( "cd ..; ls -la; cd arg_test; ls -la" );} //end main} //end main

Write a C program using Write a C program using system()system() that:that: Assumes the current working directory is arg_test 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 arg_test

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

22

Sample Uses of system()

#include <stdlib.h>#include <stdlib.h>#define command "pwd"#define command "pwd"// invoke via: // invoke via: a.out "pwd”a.out "pwd”, or via: , or via: a.out pwda.out pwd

int main( int argc, char * argv[] )int main( int argc, char * argv[] ){ // main{ // main

printf( "using string const \"pwd\"\n" );printf( "using string const \"pwd\"\n" );system( command );system( command );printf( "using argv[1] = %s\n”, argv[1] );printf( "using argv[1] = %s\n”, argv[1] );system( argv[1] );system( argv[1] );system( system( "argv[1]" "argv[1]" );); // this would be an error!// this would be an error!// the string "argv[1]" is NOT a valid shell command// the string "argv[1]" is NOT a valid shell command

} //end main} //end main

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

Or by passing-in the command through Or by passing-in the command through argv[1]argv[1]

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

23

Tricky Use of system()

#include <stdlib.h>#include <stdlib.h>#include <time.h>#include <time.h>// file name: sys7.c// file name: sys7.cint main( /* void */ )int main( /* void */ ){ // main{ // main

time_t cur_time = time( '\0' );time_t cur_time = time( '\0' );

printf( "%s", asctime( localtime( & cur_time ) ) );printf( "%s", asctime( localtime( & cur_time ) ) );printf( ”Compile and execute sys7.c\n" );printf( ”Compile and execute sys7.c\n" );system( "gcc sys7.c; system( "gcc sys7.c; a.outa.out" );" );printf( "printf( "U r rich or old when u get here U r rich or old when u get here \n\n" );" );

} //end main} //end main

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

Then compiles and runs its own source Then compiles and runs its own source sys7.csys7.c Watch out what happens with C file Watch out what happens with C file sys7.csys7.c::

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

24

Unix Commands & C Libraries

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

25

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 still render the C language rich and Libraries still render the C language rich and versatile in use; some Unix libs, commands are versatile in use; some Unix libs, commands are ubiquitous, e.g.:ubiquitous, e.g.:1. ps command2. setenv command3. signal.h lib4. stdlib.h lib5. sys/types.h lib6. time.h lib -- use for HW37. time command -- use for HW3

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

26

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 27: CS 201 Computer Systems  Programming Chapter  2 argc, argv, envp, system(), libs

27

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 28: CS 201 Computer Systems  Programming Chapter  2 argc, argv, envp, system(), libs

28

$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 shows the one PATH= PATH= line that your program line that your program did output –plus many more– scanning through did output –plus many more– scanning through envp[]envp[]

That was the line starting with That was the line starting with PATH=PATH= . /user/ . . . . /user/ . . . Or just issue command Or just issue command $PATH $PATH and observe the and observe the errorerror at the end at the 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 29: CS 201 Computer Systems  Programming Chapter  2 argc, argv, envp, system(), libs

29

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 30: CS 201 Computer Systems  Programming Chapter  2 argc, argv, envp, system(), libs

30

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 31: CS 201 Computer Systems  Programming Chapter  2 argc, argv, envp, system(), libs

31

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 32: CS 201 Computer Systems  Programming Chapter  2 argc, argv, envp, system(), libs

32

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-time cyclestracking run-time cycles 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 33: CS 201 Computer Systems  Programming Chapter  2 argc, argv, envp, system(), libs

33

C Library time

clock_t start, end, total;clock_t start, end, total; // to measure start time etc.// to measure start time etc.. . .. . .start = clock();start = clock(); // take first measurement// take first measurement. . .. . . // do compute-intensive // do compute-intensive workworkend = clock();end = clock(); // take final measurement// take final measurementtotal = end - start;total = end - start; // track time for // track time for workworkprintf( "ticks = %10u, seconds = %f\n", total,printf( "ticks = %10u, seconds = %f\n", total,

(double)( (double)total / (double)CLOCKS_PER_SEC ) );(double)( (double)total / (double)CLOCKS_PER_SEC ) );

clock_tclock_t is type to track system ticksis type to track system ticks

treat as if it were a numeric typetreat as if it were a numeric type

clock()clock() function, returning ticks function, returning ticks clock_tclock_t

CLOCKS_PER_SECCLOCKS_PER_SEC clock_tclock_t constant used to convert constant used to convert

clock ticks into secondsclock ticks into seconds

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

34

Unix Command time arg Command name:Command name: time argtime arg Purpose:Purpose: measures the time of any optional Unix measures the time of any optional Unix

command command argarg Function:Function: outputs the timing statistics to outputs the timing statistics to

standard error, asstandard error, as

elapsed timeelapsed time, ie. wall-clock time, ie. wall-clock time

user CPU timeuser CPU time, in float format, in float format

system CPU timesystem CPU time, in float format, in float format

and more . . .and more . . .

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

35

Unix Command time a.out

> time ./a.out> time ./a.out

......

real 1m41.911sreal 1m41.911suser 1m39.816suser 1m39.816ssys 0m1.957ssys 0m1.957s

Real time: Elapsed wall clock time 1 min. 41 sec.

User time: User CPU time 1 min. 39 sec

System time: System overhead CPU time 0 min. 1.9 sec.

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

36

Traditional Unix Command time> time -p ./a.out> time -p ./a.out

......

real 101.76real 101.76user 99.67user 99.67sys 1.94sys 1.94

Real time: Elapsed wall clock time 101.76 sec.

User time: User CPU time 99.67 sec

System time: System overhead CPU time 1.94 sec.

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

37

Unix C Shell Command time> time a.out> time a.out

......

99.0u 1.0s 1:41 98% 0+0k 0+0io 0pf+0w99.0u 1.0s 1:41 98% 0+0k 0+0io 0pf+0w

Default format: '%Uu %Ss %E %P %I+%Oio %Fpf+%Ww' where:

%U: User CPU time in seconds

%S: System CPU time in seconds

%E: Elapsed wall-clock time in minutes and seconds

and more ...

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

38

Other Unix Commands

isainfo –visainfo –v shows architecture detail, shows architecture detail, 32/64 bit32/64 bit ––vv verbose version gives max verbose version gives max isainfoisainfo

uname –puname –p prints product name, e.g.: prints product name, e.g.: sparcsparc

archarch manufacturer marketing name, e.g.: manufacturer marketing name, e.g.: sun4sun4

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

39

References

1.1. The C Programming Language, Second Edition: Brian The C Programming Language, Second Edition: Brian W Kernighan and Dennis M. Richie, Prentice Hall, W Kernighan and Dennis M. Richie, Prentice Hall, Englewood Cliffs, New Jersey 07632Englewood Cliffs, New Jersey 07632

2.2. time(1) man page: time(1) man page: http://linux.die.net/man/1/time

3.3. csh(1) man page: csh(1) man page: http://linux.die.net/man/1/csh