1 cs 201 computer systems programming chapter 2 argv, argc, system(), libs herbert g. mayer, psu...

45
1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Herbert G. Mayer, PSU Status 6/28/201 Status 6/28/201

Upload: tyrone-curtis

Post on 13-Dec-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

1

CS 201Computer Systems Programming

Chapter 2

argv, argc, system(), libs

Herbert G. Mayer, PSUHerbert G. Mayer, PSUStatus 6/28/201Status 6/28/201

Page 2: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

2

argc argv envp

Page 3: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

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: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

4

Definitions In C, the In C, the main()main() function returns an function returns an intint

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

In C++, the In C++, the main()main() function returns an function returns an intint type type result; yet the formal parameter list must be 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 parameters. Otherwise:specify command line parameters. Otherwise:

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

Environment variable Environment variable names names may be chosen may be chosen freely, but freely, but argcargc and and argv[]argv[] are are traditiontradition

Page 5: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

5

Definitionsint 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, i.e. why have an explicit count?, i.e. why have an explicit count?

• To allow empty-string command line parameters for To allow empty-string command line parameters for argv[]argv[]

• But But envp[]envp[] cannot identify a null environment cannot identify a null environment variable, Unix doesvariable, Unix does

not allow empty environment vars, so no count needed not allow empty environment vars, so no count needed therethere

Page 6: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

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: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

7

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

structure is provided: structure is provided: argcargc

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

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

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

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

Page 8: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

8

Reverse-Print Command Line Args

[args] a.out 3 r 55 [args] a.out 3 r 55 command line entered, prompt [args] command line entered, prompt [args]

4 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: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

9

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 command line entered, prompt [args] command line entered, prompt [args]

4 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 10: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

10

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

Page 11: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

11

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 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? Discuss or email good 3.) Other possibilities? Discuss or email good ideas, and get extra credit!ideas, and get extra credit!

Page 12: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

12

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 exists and is executable, loads your program, does ?? magic, executes your program, program, does ?? magic, executes your program, continues after exitcontinues 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 may not be modified from run to runrun

Sometimes Sometimes argc, argv, envpargc, argv, envp are accessed during are accessed during execution, other times notexecution, other times not

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

13

Student ExerciseStudents write a C program in class, that:Students write a C program in class, that:

1.1. Prints its sole argument passed to the Prints its sole argument passed to the a.outa.out commandcommand

2.2. Or, if none was provided, prints the string Or, if none was provided, prints the string “<none>”“<none>”

Page 14: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

14

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

NAMENAMEset, 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 Current environment variables used in your Unix environment are tracked and can be output for any of environment are tracked and can be output for any of your processesyour processes

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

Each such string contains one of your process’ Each such string contains one of your process’ environment variablesenvironment variables

Page 15: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

15

Sample envp Version in C

// program to print all environment variables// program to print all environment variables// one per line// one per line// practice: char * envp[]// practice: char * envp[]////int main( int argc, char ** argv, char * envp[] )int main( int argc, char ** argv, char * envp[] ){ // main{ // main

int index = 0;int index = 0; // note: argc and argv are ignored here, but are specified!!// note: argc and argv are ignored here, but are specified!!

while( envp[ index ] ) { // OK to assume null-terminationwhile( envp[ index ] ) { // OK to assume null-termination// print one environment variable at a time// print one environment variable at a time

printf( "printf( "env ... %d = env ... %d = \"%s\"\n", index+1, envp[ index++ ] );\"%s\"\n", index+1, envp[ index++ ] );} //end while} //end whileprintf( "Number of environment vars = %d\n", index );printf( "Number of environment vars = %d\n", index );

exit( 0 );exit( 0 );} //end main} //end main

Page 16: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

16

Sample envp, Counting from 1

environment variable 1 environment variable 1 = "USER=herb“= "USER=herb“ <- 1 only to avoid counting from 0 <- 1 only to avoid counting from 0 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 more. . . And 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 17: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

17

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 18: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

18

References

1.1. http://crasseux.com/books/ctutorial/argc-and-http://crasseux.com/books/ctutorial/argc-and-argv.html 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/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 19: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

19

system()

Page 20: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

20

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

a shell command; causes error as a shell a shell command; causes error as a shell commandcommand

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 via a shell commandtyped via a shell command

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

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

Page 21: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

21

system( “string” )

Completed (last) command returns with Completed (last) command returns with exit status in exit status in waitpid(3)waitpid(3) format, which format, which is passed to the invoking C programis passed to the invoking C program

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

waitpidwaitpid 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 22: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

22

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

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

Sample shown below:Sample shown below:

Page 23: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

23

Sample Uses of system()

Students, you know the Unix command Students, you know the Unix command lsls

If not, now is a good time to ask for If not, now is a good time to ask for clarification clarification

Also you understand the meaning of the Also you understand the meaning of the

symbolic directory named symbolic directory named .. and and .... And you know the And you know the cdcd command to change the command to change the

current directory in Linux + Unixcurrent directory in Linux + Unix

Let’s use them all now in the Let’s use them all now in the system()system() functionfunction

Page 24: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

24

Sample Uses of system()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 .. a level up the directory hierarchy

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 25: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

25

Sample Uses of system()You students do this now, in class!You students do this now, in class!

We’ll show you later We’ll show you later

Page 26: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

26

Sample Uses of system()

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

// // assumeassume execution in directory arg_test 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 27: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

27

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[] ) // ignore envp[]// ignore envp[]{ // 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 C program that prints the current working directory by using directory by using system()system(), specifying , specifying string literal string literal “pwd”“pwd”

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

Page 28: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

28

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 Write a C program sys7.csys7.c using using system()system() that prints the current date/timethat prints the current 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 29: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

29

Unix Commands & C Libraries

Page 30: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

30

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

used, yet offering only limited high-used, yet offering only limited high-level language facilitieslevel 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 Libraries still render the C language

richrich and and versatileversatile; some Unix libs, and ; some Unix libs, and Unix commands are ubiquitous, e.g.:Unix commands are ubiquitous, e.g.:1. ps command2. setenv command3. signal.h lib4. stdlib.h lib5. sys/types.h lib6. time.h lib7. time command

Page 31: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

31

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 processesactive processes Without options, Without options, psps lists lists allall processes processes

with same effective user ID and 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 32: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

32

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.term=vt100=term=vt100=[herb][herb]

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 33: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

33

$PATH, etc. on Unix System On Unix shell, issue command On Unix shell, issue command man man

shell_builtins shell_builtins and learn about several and learn about several interesting commands, e.g.:interesting commands, e.g.:

alias echo $PATH setenv

Command Command echo $PATH echo $PATH shows the one shows the one PATH= PATH= line line that your program did output –plus many that your program did output –plus many more– scanning through 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. Why an at the end. Why an error?error?

Again you will see a path for all Again you will see a path for all directories searched, in order, to resolve a directories searched, in order, to resolve a command --or finding a file-- you specifiedcommand --or finding a file-- you specified

Page 34: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

34

$PATH, etc. on Unix Systems

Command Command setenvsetenv without arguments without arguments will provide information that your will provide information that your program outputs, when scanning program outputs, when scanning through 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 setenv PATH $PATH\:/u/herb/progs$PATH\:/u/herb/progs, , will add will add /u/herb/progs/u/herb/progs at the end of at the end of existing pathexisting path

Page 35: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

35

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

application application processesprocesses 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 communicationinterprocess communication in Unix 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) occurred. specific event (the signal) occurred. Some functions set, others remove etc. Some functions set, others remove etc. event recording. If process has 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 36: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

36

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 37: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

37

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 38: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

38

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 const struct tm*tm*

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

39

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 is type to track system ticksticks

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

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

CLOCKS_PER_SECCLOCKS_PER_SEC clock_tclock_t constant used to constant used to convertconvert

clock ticks into secondsclock ticks into seconds

Page 40: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

40

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

optional Unix command optional Unix command argarg Function:Function: outputs the timing statistics outputs the timing statistics

to to standard errorstandard error, as, as

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

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

system CPU timesystem CPU time, in float , in float formatformat

and more . . .and more . . .

Page 41: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

41

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 42: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

42

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 43: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

43

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 ... Varies with Unix or Linux

Page 44: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

44

Other Unix Commands

isainfo –visainfo –v shows ISA architecture detail, shows ISA architecture detail, 32/64 bit32/64 bit

––vv verbose version gives max verbose version gives max isainfoisainfo

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

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

Page 45: 1 CS 201 Computer Systems Programming Chapter 2 argv, argc, system(), libs Herbert G. Mayer, PSU Status 6/28/201

45

References

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

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

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