Mohammed Farragmfarrag@freebsd.orghttp://wiki.freebsd.org/MohammedFarrag
Perl Programming Language.FreeBSD AdministrationOverview
Every UNIX program in Perl should start with#!/usr/bin/perlEvery variable should start with $ whatever it points to.Arrays are manipulated using @ .Hashes are manipulated using %.Comments start with #.Perl Programming Language
Scalar is a number or string.Examples    $scalarint = 42;    $scalarfp = 1.01;    $scalarstr = "A string is a scalar";Scalars
An array is an indexed list of values with a consistent order.Names of arrays are prefixed with @. Indices counting from zero.Examples    @first_array = (1, 2, 3, 4);     @second_array = ('one', '2', 'three', '4', '5');Arrays
Hashes, also called associative arrays, are tables of key-value pairs. Names of hashes are prefixed with %. Example:   %hash = ('Mouse', 'Jerry', 'Cat', 'Tom', 'Dog', 'Spike');%hash = (Mouse => 'Jerry', Cat => 'Tom', Dog => 'Spike');You can access ‘Spike’ using $hash{Dog}Hashes
A reference is an immutable pointer to a value in memory, which may be any data type: scalar, array, hash, and so on.        $scalarref = \$scalar;        $arrayref = \@array;To get to the original value, we dereference the reference by prefixing it with the symbol of the underlying data type.$$reftostring;@$arrayref;References
A subroutine is a block that is declared for reuse with the sub keyword. Examples   sub red_october {     print "A simple sub\n";   }To call this subroutine, we can now just write any of the following:red_october;    &red_october;red_october();Subroutine
A package is a Perl namespace, a logical subdivision of compiled code in which variables and subroutines can reside.The usekeyword by contrast loads a module at compile time, before other code is compiled, and calls an import routine in the just-loaded module to import variables and subroutines into the package of the caller.  use File::Basename 'basename','dirname';Packages
Warnings    Warnings can be enabled in three ways: through the -w option, the special variable $^W, or the use warnings pragma.Strictness    This enables additional checks that our code must pass at compile time before the interpreter will execute it. This is almost always a good thing to do.    strict modes: vars, refs, and subs.Warnings and Strictness
The crypt function performs a one-way transform of the string passed; it is identical to (and implemented using) the C library crypt on Unix systems, which implements a variation of the Data Encryption Standard (DES) algorithm.@characters = (0..9, 'a'..'z' ,'A'..'Z', '.', '/');$encrypted = crypt($password, @characters[rand 64, rand 64]);Password Encryption: crypt
# check passworddie "Wrong!" unless crypt($entered, $encrypted) eq $encrypted;crypt – cont’d
$good_egg = "Humpty" . "Dumpty";   # produces "HumptyDumpty“"abc" x 3; # produces 'abcabcabc'String and List Operators
Number of elements in an array using scalar  $count = scalar(@array); Last index in an array using $#$highest = $#array; # $highest = scalar(@array)-1Append an element to the array$array[scalar(@array)] push @arrayInsert at the beginningunshift @arrayTruncating and resizing@array = @array[0..3];Array Manipulation
first: Return the first element of the list for which a condition is true.max, min: Return the highest and lowest numerical value, respectively.maxstr, minstr: Return the highest and lowest alphabetical value, respectively.sum: Return the sum of the list evaluated numerically.shuffle: Return the list in a random order.reduce: Reduce a list to a single value by arbitrary criteria.Array Manipulation - cont’d
Use <STDIN> to receive the input from the user.Keyboard Handling
Example	1	#!/usr/bin/perl	2	# Fig. 2.17: fig02_17.pl	3	# Using if statements with relational and equality operators	4		5	print "Please enter first integer: ";	6	$number1 = <STDIN>;	7	chomp $number1;	8		9	print "Please enter second integer: ";	10	$number2 = <STDIN>;	11	chomp $number2;	12		13	print "The integers satisfy these relationships:\n";	14		15	if ( $number1 == $number2 ) {	16	   print "$number1 is equal to $number2.\n";	17	}	18		19	if ( $number1 != $number2 ) {	20	   print "$number1 is not equal to $number2.\n";	21	}	22		23	if ( $number1 < $number2 ) {	24	   print "$number1 is less than $number2.\n";	25	}	26		27	if ( $number1 > $number2 ) {	28	   print "$number1 is greater than $number2.\n";	29	}	30
Array Looping Example	1	#!/usr/bin/perl	2	# Fig. 4.3: fig04_03.pl	3	# Looping through an array with the for repetition structure.	4		5	@array = ( "Hello", 283, "there", 16.439 );	6		7	# display every element of the array	8	for ( $i = 0; $i < 4; ++$i ) {	9	   print "$i   $array[ $i ]\n";	10	}0   Hello1   2832   there3   16.439
Data HierarchySallyBlackTomBlueFileJudyGreenIrisOrangeRandyRedRecordJudyGreenFieldJ u d yByte (ASCII character J)01001010Bit1
OpenSeekTruncatePrintcloseFile Processing
File Manipulation	1	#!usr/bin/perl	2	# Fig. 10.6: fig10_06.pl	3	# Demonstrating writing to and reading from a file.	4		5	use strict;	6	use warnings;	7		8	print( "Opening file for output\n" );	9	open( OUTFILE, ">file.txt" ) 	10	or die( "Can't find file.txt : $!" );	11	print( "Outputting to file\n" );	12	print( OUTFILE "There was an old lady\n" );	13	close( OUTFILE ) or die( "Can not close file.txt: $!" );	14		15	print "The file now contains:\n";	16	open( INFILE, "file.txt" ) 	17	or die( "Can not open file.txt: $!" );	18	print while ( <INFILE> );	19	close( INFILE ) or die( "Can not close file.txt: $!" );	20		21	print( "\nAppend to the end of the file\n" );	22	open( OUTFILE, ">>file.txt" ) 	23	or die( "Can not open file.txt: $!" );	24	print( OUTFILE "who lived in a shoe.\n" );	25	close( OUTFILE ) or die( "Can not close file.txt: $!" );	26		27	print( "It now reads:\n" );
	28	open( INFILE, "file.txt" ) 	29	or die( "Can not open file.txt: $!" );	30	print while ( <INFILE> );	31	close( INFILE ) or die( "Can not close file.txt: $!" );Opening file for outputOutputting to fileThe file now contains:There was an old lady Append to the end of the fileIt now reads:There was an old ladywho lived in a shoe.
Exclusive Locking Example	1	#!/usr/bin/perl	2	# Fig. 10.11: fig10_11.pl	3	# Logs visitors to web site.	4		5	use strict;	6	use warnings;	7	use CGI qw( :standard );	8	use Fcntl qw( :flock );	9		10	my @vars = 	11	qw( REMOTE_ADDR REMOTE_PORT REQUEST_URI QUERY_STRING );	12	my @stuff = @ENV{ @vars };	13	my $info = join( " | ", @stuff );	14		15	open( FILE, "+>>log.txt" )	16	or die( "Could not open log.txt: $!" );	17	flock( FILE, LOCK_EX )	18	or die( "Could not get exclusive lock: $!" );	19	print( FILE "$info\n\n" );	20	flock( FILE, LOCK_UN ) or die( "Could not unlock file: $!" );	21		22	close( FILE );	23		24	if ( $stuff[3] ne "" ) {	25	   print( header( -Refresh=> '5; URL=http://www.google.com' ) );	26	   print( start_html( "log.txt" ) );	27	   print( h1( "Welcome to Deitel & Associates, $stuff[3]!\n" ) );	28	   print( p( i( "You will now be redirected to our home page." ) ) );	29	}
The @ARGV array contains all the arguments that were passed to our program when it was started. The definition of what defines an “argument” depends not on Perl, but on the shell that was used to start our program. However, in most cases spaces separate arguments from one another.The @ARGV Array
perlmyscript -u sventek -p cuckooExample
# number of arguments passed   scalar(@ARGV); # highest element = no. of arguments -1   $#ARGV;
	1	#!/usr/bin/perl	2	# Fig. 11.2: fig11_02.pl	3	# A program that uses file tests	4		5	use strict;	6	use warnings;	7		8	foreachmy $file ( @ARGV ) {	9	   print( "Checking $file: " );	10		11	if ( -e $file ) {        # does file exist?	12	      print( "$file exists!\n" );	13		14	if ( -f $file ) {     # is the file a plain file?	15	         print( "The file $file is:" );	16	         print( " executable" ) if ( -x $file );  # executable?	17	         print( " readable" ) if ( -r $file );    # readable?	18	         print( " writable" ) if ( -w $file );    # writable?	19	         print( "\n" );	20	         print( "It is ", -s $file, " bytes.\n" ); # size	21	my @time = timeconv( -A $file );          # accessed	22	         print( "Last accessed at $time[0] days, ",	23	                "$time[1] hours, $time[2] minutes ",	24	                "and $time[3] seconds.\n" );	25	         @time = timeconv( -M $file );             # modified	26	         print( "Last modified at $time[0] days, ",	27	                "$time[1] hours, $time[2] minutes, ",	28	                "and $time[3] seconds ago.\n" );	29	      }
2 ways for concurrencyProcessEach task has its own separate memory spaceLess portableMultithreadingUse the same memory processThe race conditionThe timing of threadsSynchronizationNot possible with processesEach knows when its data area is manipulatedProcess Management
ways to forkCall the systems fork commandNot always availableForkParent processCalls the fork functionChild processCreated by the fork functionEach has a process id or pidParent returns child pid and undef if unsuccessfulChild returns 0The fork command
	1	#!/usr/bin/perl	2	# Fig. 18.1: fig18_01.pl	3	# Using fork to create child processes.	4		5	use warnings;	6	use strict;	7		8	my ( $start, $middle, $end, $pid );	9	$| = 1;	10		11	$start = time();	12	A call is made to the fork function cloning the current process13if ( $pid = fork() ) {	14	   sleep( 1 );	15	   print( "Parent executing.\n" );	16	   sleep( 2 );	17	   print( "Parent finished.\n" );	18	}19elsif ( defined( $pid ) ) {Executes in the child process	20	   sleep( 1 );	21	   print( "Child executing.\n" );22   sleep( 2 );Sleep is used to slow the program down	23	   print( "Child finished.\n" );	24	   exit();	25	}	26	else {	27	   die( "Could not fork" );	28	}	29
	30	$middle = time();	31		32	print( "That took " );	33	print( $middle - $start );The time is used to compare using a process and not	34	print( " seconds with fork.\n" );	35		36	sleep( 3 );	37	sleep( 3 );38$end = time();	39		40	print( "That took " );	41	print( $end - $middle );	42	print( " seconds without fork.\n" );	43	print( "Total of ", ( $end - $start ), " seconds.\n" );Parent executing.Child executing.Parent finished.Child finished.That took 3 seconds with fork.That took 6 seconds without fork.Total of 9 seconds.
	1	#!/usr/bin/perl	2	# Fig. 18.2: fig18_02.pl	3	# Demonstrates the wait function.	4		5	use warnings;	6	use strict;	7		8	my ( $pid, $pid2 );	9	$| = 1;	10	Create two forks for a total of three processes11if ( ( $pid = fork() ) && ( $pid2 = fork() ) ) {	12	   print( "I have to wait for my kids.\n" );	13	my $straggler = wait();14   print( "Finally $straggler finished, now I can go.\n" );	15	}16elsif ( $pid && defined( $pid2 ) ) {Will not print until all the children are done	17	   sleep( 2 );	18	   print( "Kid 2: So is mine...\n" );	19	   sleep( 4 );	20	   exit();Child 1	21	}22elsif ( defined( $pid ) ) {	23	   sleep( 1 );Child 2	24	   print( "Kid 1: My parent is patient...\n" );	25	   sleep( 2 );	26	}	27	else {	28	   die( "Forking problems: " );	29	}I have to wait for my kids.Kid 1: My parent is patient...Kid 2: So is mine...Finally 296 finished, now I can go.
	1	#!/usr/bin/perl	2	# Fig. 18.3: fig18_03.pl	3	# Demonstrating the waitpid function.	4		5	use warnings;	6	use strict;	7		8	my ( $pid, $pid2 );	9	$| = 1;	10	Since two fork methods are called then there will be 3 processes11if ( ( $pid = fork() ) && ( $pid2 = fork() ) ) {	12	   print( "I have to wait for my kids.\n" );13my $straggler = waitpid( $pid, 0 );	14	   print( "Finally $straggler finished, now I can go.\n" );	15	}	16	elsif ( $pid && defined( $pid2 ) ) {The waitpid function will cause the the third process to wait until the first process is finished	17	   sleep( 2 );	18	   print( "Kid 2: Mine is not...\n" );	19	   sleep( 4 );	20	   print( "Kid 2: Hey! Wait for me!!!\n" );	21	   exit();	22	}	23	elsif ( defined( $pid ) ) {	24	   sleep( 1 );	25	   print( "Kid 1: My parent is patient...\n" );	26	   sleep( 2 );	27	}	28	else {	29	   die( "Forking problems: " );	30	}
I have to wait for my kids.Kid 1: My parent is patient...Kid 2: Mine is not...Finally 269 finished, now I can go.Kid 2: Hey! Wait for me!!!
The exec functionUsed to execute other programs from a programUses system shell to invoke a programNow program replaces current program’s processWhen new program terminates so does the old oneArguments passed is the program openedAll wild cards that work on the system are validIf a list is passedFirst is the programThe rest of the list is arguments to pass to that command without system processingThe system and exec functions
The system functionSame as exec functionThe only difference is that the process is returned to the program when the opened program terminatesThis is done using a fork function and making one waitThe system and exec functions (II)
	1	#!/usr/bin/perl	2	# Fig. 18.4: fig18_04.pl	3	# Uses the system function to clear the screen.	4		5	use warnings;	6	use strict;	7		8	print( "What file would you like to create? " );Used to determine the OS that the program is running in. Will only work in Windows or when the command clear works	9	chomp( my $file = <STDIN> );	10	11( $^O =~ /Win/ ) ? system( "cls" ) : system( "clear" );	12		13	print( "Type the text you wish to be in this file.\n" );	14	print( "Type clear on a blank line to start over.\n" );	15	print( "Type quit on a blank line when you are finished.\n" );	16	open( FILE, ">$file" ) or die( "Cannot open: $!" );	17	Creates a loop that will continue until the user enters “quit”	18while ( <STDIN> ) {	19	lastif ( /quit/ );	20		21	if ( /clear/ ) {	22	      ( $^O =~ /Win/ ) ? system( "cls" ) : system( "clear" );	23	      print( "Type the text you wish to be in this file.\n" );	24	      print( "Type clear on a blank line to start over.\n" );Opens the file to write to	25	      print( "Type quit on a blank line " );	26	      print( "when you are finished.\n" );27      open( FILE, ">$file" ) or die( "Cannot open: $!" );	28	   }
	29	else {Prints to the file30      print( FILE );	31	   }Closes the file	32	}	33	34close( FILE ) or die( "Cannot close: $!" );What file would you like to create? hello.plType the text you wish to be in this file.Type clear on a blank line to start over.Type quit on a blank line when you are finished.#!/usr/bin/perl# hello.pl# Typical "hello world" program. use warnings;use strict; print( "Hello World" );quit
	1	#!/usr/bin/perl	2	# Fig. 18.6: fig18_06.pl	3	# Gets a web page and opens for editing.	4		5	use warnings;Will only open URLs that begin with http://	6	use strict;	7	use LWP::Simple;	8	If the OS is windows then the program opens notepad, or else it will open vi	9	my( $URL, $filename ) = @ARGV;Uses the exec function to open the desired program and file	10	11if ( $URL !~ m#http://# ) {	12	   $URL =~ s#^#http://#;	13	}	14		15	if ( is_error( getstore( $URL, $filename ) ) ) {	16	   die( "Could not get file: $!" );	17	}	18	19my $program = ( $^O =~ /Win/ ? "notepad.exe" : "vi" );	20	21exec( $program, $filename );
The open functionPlaces a pipe symbol (|) in the string that specifies the command to be executed.If at the front the input of a file is attached to a file handleIf at the end the output of a file is attached to a file handleWrite to the handle to modify the inputRead from the handle to modify the outputThe open2 functionAllows the use of both STDIN and STDOUTThe open3 functionAllows the programmer to obtain the STDERRControlling the Input and Output of Processes
	1	#!/usr/bin/perl	2	# Fig. 18.7: fig18_07.pl	3	# Demonstrating using open to connect different processes.Connects the STDOUT to the handle DIR	4		5	use warnings;Connects MORE to STDINWrites data to MORE	6	use strict;	7	Closes the pipes8open( DIR, "dir *.* |" ) or die( "Cannot open dir pipe: $!" );9open( MORE, "| more" ) or die( "Cannot open more: $!" );	10		11	while ( <DIR> ) {12   print( MORE );	13	}	14	15close( DIR ) or die( "Cannot close DIR: $!" );	16	close( MORE ) or die( "Cannot close MORE: $!" );
	1	#!/usr/bin/perl	2	# Fig. 18.8: fig18_08.pl	3	# Demonstrates using backticks.	4		5	use warnings;	6	use strict;	7		8	my $date;	9	my $version;	10	If the operating system is Windows then display the version and the date11if ( $^O =~ /Win/ ) {	12	   $version = ( `ver` );	13	   $date = ( `date /t` );	14	}15else {If the OS is not Windows then use a different method to display its version and date	16	   $version = ( `uname -r -s` );	17	   $date = ( `date` );	18	}	19		20	print( "The Operating system version is $version");	21	print( "\n", $date );The Operating system version is Microsoft Windows 2000 [Version 5.00.2195] Tue 11/28/2000 The Operating system version is Linux 2.2.14-6.1.1 Tue Nov 28 06:26:43 EST 2000
	1	#!/usr/bin/perl	2	# Fig. 18.9: fig18_09.pl	3	# Demonstrating the open2 function.Uses IPC::Open2 to allow for both input and output to be attached to a file handle	4		5	use warnings;Executes fig18_10.pl	6	use strict;7use IPC::Open2;Alters the output that fig18_10.pl would display	8		9	$| = 1;	10	my $command = 'perl fig18_10.pl';	11	12open2( \*INPUT, \*OUTPUT, $command ) or	13	   die( "Cannot open: $!" );	14		15	for ( 1 .. 20 ) {16   print( OUTPUT $_, "\n" );	17	my $read = <INPUT>;	18	   print( $_, '  ', $read );	19	}	20		21	close( OUTPUT ) or die( "Cannot close OUTPUT: $!" );	22	close( INPUT ) or die( "Cannot close INPUT: $!" );
1  MyItnkr.UtBnc2  My6jwfxg7zFGE3  My3G3DtIRpQEA4  Myza94uYasdEE5  MyCBteM4CIuTk6  MyWRtG.HnvdL27  Myb8qLeBJ6TlM8  MyE6k76L3NeoE9  MyxpYOghD0TIE10  MyI8Uhkz4HPjY11  MyB3G7m.CDII612  MyugXM4mJTc1c13  My9OUTHS6M.jg14  My8UYE/LL8dgU15  MyYAcz4F1r.to16  MycPbNadoaNYo17  MyXdTeyyclDNY18  MyTm8RxjwtKO.19  My2Q98KujB0i620  MyecGYzUxpdvk
	1	#!/usr/bin/perl	2	# Fig. 18.10: fig18_10.pl	3	# Helper to fig18_09.pl.	4		5	use warnings;	6	use strict;	7		8	$| = 1;	9		10	while ( <STDIN> ) {11   print( crypt( $_, "My cats' breath smells like cat food“ ));	12	   print( "\n" );	13	}A simple program the displays this line for output after being encrypted
The pipe functionUsed to connect file handles of parent and children programsAllows them to communicate to each otherShould set $| to flush after each outputHelps to prevent deadlockUsing open with filename “-”Returns a handle that is a duplicate of STDIN or STDOUTCommunicating Between Processes
	1	#!/usr/bin/perl	2	# Fig. 18.11: fig18_11.pl	3	# Using pipe to communicate with child processes.	4		5	use warnings;	6	use strict;	7	use IO::Handle;	8	Links the parent input with the child output, and visa versa9pipe( CHILDINPUT, PARENTOUTPUT );	10	pipe( PARENTINPUT, CHILDOUTPUT );	11		12	PARENTOUTPUT->autoflush( 1 );	13	CHILDOUTPUT->autoflush( 1 );	14	STDOUT->autoflush( 1 );	15	16if ( my $pid = fork() ) {Forks the program	17	18for ( 1 .. 10 ) {Loops ten times displaying its output and the child’s output	19	      print( PARENTOUTPUT "$_\n" );	20	      print( "I said $_, " );	21	      chomp( my $response = <PARENTINPUT> );	22	      print( "and he said $response!\n" );	23	   }	24	25   close( PARENTOUTPUT ) orCloses the parent input and output handles	26	      die( "Cannot close PARENTOUTPUT: $!" );	27	   close( PARENTINPUT ) or	28	      die( "Cannot close PARENTINPUT: $!" );	29	}
The child code30elsif ( defined( $pid ) ) {31   close( PARENTOUTPUT ) orCloses the parent input and output	32	      die( "Cannot close PARENTOUTPUT: $!" );	33	   close( PARENTINPUT ) or	34	      die( "Cannot close PARENTINPUT: $!" );	35	36while ( <CHILDINPUT> ) {Prints out the parent output multiplied by 20	37	      chomp();	38	      print( CHILDOUTPUT $_ * 20, "\n" );	39	   }	40	41   close( CHILDOUTPUT ) orCloses the child input and output	42	      die( "Cannot close CHILDOUTPUT: $!" );	43	   close( CHILDINPUT ) or	44	      die( "Cannot close CHILDINPUT: $!" );	45	   exit();	46	}	47	else {	48	   die( "Fork did not work" );	49	}	50		51	print( "And that is the end of the conversation.\n" );I said 1, and he said 20!I said 2, and he said 40!I said 3, and he said 60!I said 4, and he said 80!I said 5, and he said 100!I said 6, and he said 120!I said 7, and he said 140!I said 8, and he said 160!I said 9, and he said 180!I said 10, and he said 200!And that is the end of the conversation.
	1	#!/usr/bin/perl	2	# Fig. 18.12: fig18_12.pl	3	# Using open to fork and filter output.	4		5	use warnings;	6	use strict;	7		8	$| = 1;	9	This will create a copy of the input in a file handle10if ( my $pid = open( CHILD, "-|" ) ) {	11	my $i;	12	Displays the line number13while ( <CHILD> ) {	14	      print( "Line ", ++$i, ": $_" );	15	   }	16		17	   close( CHILD ) or die( "Cannot close: $!" );	18	}Will output the lines synchronized with the line number output19elsif ( defined( $pid ) ) {	20	   print( "I am doing some\n" );	21	   print( "processing here\n" );	22	   print( "that produces\n" );	23	   print( "multiple lines\n" );	24	   print( "of output.\n" );	25	   exit();	26	}	27	else {	28	   print( "Could not fork." );	29	}Line 1: I am doing someLine 2: processing hereLine 3: that producesLine 4: multiple linesLine 5: of output.
SignalsMessages that are delivered to a program by the OSAllow processes to communicate with one anotherSignals are generated by several thingsErrorsEventsUser inputInternally from a programMost signals can be overriddenSIGKILL and SIGSTOP cannot be overriddenUsed as a last resort for programs that stop respondingSignals Handling
Special Signals__DIE__ (two underscores (_))Used to override the die commandNot effective when first invokedPrevents infinite recursion__WARN__Used to override the warn commandDEFAULTReturns a signal to its original stateIGNOREIgnores a signalSignals Handling (II)
Signal Handling
	1	#!/usr/bin/perl	2	# Fig. 18.14: fig18_14.pl	3	# Demonstrates using %SIG to define our own signal handlers.	4		5	use warnings;Every time SIGINT is used it calls the stop function	6	use strict;Prints out Hooray! every second as long as $count does not equal zero	7		8	my $count = 3;Subtracts one from the counter and displays it	9	$| = 1;	10	11$SIG{ 'INT' } = \&stop;	12	13while ( $count ) {	14	   print( "Hooray!" );	15	   print( "\n" );	16	   sleep( 1 );	17	}	18		19	sub stop	20	{	21	   $SIG{ 'INT' } = \&stop;22   $count--;	23	   print( "$count\n" );	24		25	unless ( $count ) {	26	      print( "Sorry, I did not want to stop...\n" );	27	   }	28	}
Hooray!Hooray!2Hooray!Hooray!Hooray!1Hooray!0Sorry, I did not want to stop...
The kill functionUsed to send signals to another processFirst argument is the signal to be sentRest of the arguments are the processes to send the signal toTerminating childrenLeave behind zombies in process tableAllow parent to figure out if the child ended normallyReaping is performed to eliminate zombiesUse the wait or waitpid functions to do additional operationsThe IGNORE statement is used to remove the children from the tableSending Signals
	1	#!/usr/bin/perl	2	# Fig. 18.15: fig18_15.pl	3	# Sending signals to child processes using kill.	4		5	use warnings;	6	use strict;	7	use POSIX qw( :signal_h :errno_h :sys_wait_h );	8	9$SIG{ USR1 } = \&user1;Calls the desired functions	10	$SIG{ USR2 } = \&user2;	11	$| = 1;	12		13	sub user1 	14	{	15	   $SIG{ USR1 } = \&user1;Displays when the signal is received16   print( "I have received SIGUSR1.\n" );	17	}	18		19	sub user2 	20	{	21	   $SIG{ USR2 } = \&user2;	22	   print( "I have received SIGUSR2.\n" );	23	}	24
	25	if ( my $pid = fork() ) {Sends a signal using the kill function26   kill( 'USR1', $pid );	27	   kill( 'USR2', $pid );	28	   print( "I have just sent two signals.\n" );	29	   sleep( 2 );	30	   print( "Now I am going to send a few more.\n" );	31	   kill( USR2 => $pid );	32	   kill( USR1 => $pid );	33	   print( "Parent done.\n" );	34	}	35	elsif ( defined( $pid ) ) {	36	   sleep( 5 );	37	   print( "Kid done.\n" );	38	   exit();	39	}	40	else {	41	   print( "Forking error...\n" );	42	}	43		44	wait();fig18_15.plProgram OutputI have just sent two signals.I have received SIGUSR2.I have received SIGUSR1.Now I am going to send a few more.Parent done.I have received SIGUSR2.I have received SIGUSR1.Kid done.
Install new port.Mounting and Unmounting File SystemsConfigure interface.Soft/Hard Linking.FreeBSD Administration
Adding Packagespkg_add -r lsof-4.56.4Deleting Packagespkg_delete xchat-1.7.1Packages
Makefile: The Makefile contains various statements that specify how the application should be compiled and where it should be installed on your systemdistinfo file: This file contains information about the files that must be downloaded to build the port, and checksums, to ensure that those files have not been corrupted during the download.files directory: This directory contains patches to make the program compile and install on your FreeBSD system. This directory may also contain other files used in building the port.pkg-comment file: This is a one-line description of the program.pkg-descr file: This is a more detailed, often multiple-line, description of the program.pkg-plist file: This is a list of all the files that will be installed by the port. It also tells the ports system what files to remove upon deinstallation.Port Installation
# whereislsoflsof/usr/ports/sysutils/lsofNote: You must be the root user to install ports.# cd /usr/ports/sysutils/lsofExample
make>> lsof_4.57D.freebsd.tar.gz doesn't seem to exist in /usr/ports/distfiles/. >> Attempting to fetch from file:/cdrom/ports/distfiles/.===> Extracting for lsof-4.57 ... [extraction output snipped] ... >> Checksum OK for lsof_4.57D.freebsd.tar.gz. ===> Patching for lsof-4.57 ===> Applying FreeBSD patches for lsof-4.57 ===> Configuring for lsof-4.57 ... [configure output snipped] ... ===> Building for lsof-4.57 ... [compilation snipped] ... #
# make install===> Installing for lsof-4.57 ... [install routines snipped] ... ===> Generating temporary packing list ===> Compressing manual pages for lsof-4.57 ===> Registering installation for lsof-4.57===> SECURITY NOTE: This port has installed the following binaries which execute with increased privileges.
# cd /usr/ports/irc/lsof# make deinstall===> Deinstalling for lsof-4.57 Removing Installed Ports
/etc/fstab FileThe /etc/fstab file contains a list of lines of the following format:   device     /mount-point fstype       options    dumpfreqpassnmount-point:  directory on which to mount the file system.fstype: The file system type to pass to mount. The default FreeBSD file system is ufs.Options: Either rw for read-write file systems, or ro for read-only file systems, followed by any other options that may be needed. A common option is noauto for file systems not normally mounted during the boot sequence. dumpfreq:  This is used by dump to determine which file systems require dumping. If the field is missing, a value of zero is assumed.passno: This determines the order in which file systems should be checked. Mounting and Unmounting File Systems
In its most basic form, you use:      # mount devicemountpoint-a  Mount all the file systems listed in /etc/fstab. Except those marked as “noauto”, excluded by the -t flag, or those that are already mounted.-d  Do everything except for the actual mount system call. This option is useful in conjunction with the -v flag to determine what mount is actually trying to do.-f  Force the mount of an unclean file system (dangerous), or forces the revocation of write access when downgrading a file system's mount status from read-write to read-only.-r  Mount the file system read-only. This is identical to using the ro argument to the -o option.The mount command
Through sysinstall -> configure -> Networking -> InterfacesUse ifconfig command as follows:ifconfig interface inet IP         Example:ifconfiglnc0 inet 202.54.1.22Notes: To setup up ip permanently open file /etc/rc.conf ; add/modify        network entries:ee/etc/rc.conf
 Setup values as follows:hostname="fbsdx.test.com"ifconfig_lnc0="inet 192.168.0.6 netmask 255.255.255.0"
Ethernet interface name can be Obtained using ifconfig -a command.
You should run /etc/netstartscript or /etc/rc.d/netif restart.Interface Configuration
a hard link is a pointer to the file's i-node. a soft link, also called symbolic link, is a file that contains the name of another file. We can then access the contents of the other file through that name. That is, a symbolic link is like a pointer to the pointer to the file's contents.Hard Links Vs. Soft Links
Pointers to programs, files, or directories located elsewhere (just like Windows shortcuts)
If the original program, file, or directory is renamed, moved, or deleted, the soft link is broken. 
If you type ls -F you can see which files are soft links because they end with @

Lecture 3 Perl & FreeBSD administration

  • 1.
  • 2.
    Perl Programming Language.FreeBSDAdministrationOverview
  • 3.
    Every UNIX programin Perl should start with#!/usr/bin/perlEvery variable should start with $ whatever it points to.Arrays are manipulated using @ .Hashes are manipulated using %.Comments start with #.Perl Programming Language
  • 4.
    Scalar is anumber or string.Examples $scalarint = 42; $scalarfp = 1.01; $scalarstr = "A string is a scalar";Scalars
  • 5.
    An array isan indexed list of values with a consistent order.Names of arrays are prefixed with @. Indices counting from zero.Examples @first_array = (1, 2, 3, 4); @second_array = ('one', '2', 'three', '4', '5');Arrays
  • 6.
    Hashes, also calledassociative arrays, are tables of key-value pairs. Names of hashes are prefixed with %. Example: %hash = ('Mouse', 'Jerry', 'Cat', 'Tom', 'Dog', 'Spike');%hash = (Mouse => 'Jerry', Cat => 'Tom', Dog => 'Spike');You can access ‘Spike’ using $hash{Dog}Hashes
  • 7.
    A reference isan immutable pointer to a value in memory, which may be any data type: scalar, array, hash, and so on. $scalarref = \$scalar; $arrayref = \@array;To get to the original value, we dereference the reference by prefixing it with the symbol of the underlying data type.$$reftostring;@$arrayref;References
  • 9.
    A subroutine isa block that is declared for reuse with the sub keyword. Examples sub red_october { print "A simple sub\n"; }To call this subroutine, we can now just write any of the following:red_october; &red_october;red_october();Subroutine
  • 10.
    A package isa Perl namespace, a logical subdivision of compiled code in which variables and subroutines can reside.The usekeyword by contrast loads a module at compile time, before other code is compiled, and calls an import routine in the just-loaded module to import variables and subroutines into the package of the caller. use File::Basename 'basename','dirname';Packages
  • 11.
    Warnings Warnings can be enabled in three ways: through the -w option, the special variable $^W, or the use warnings pragma.Strictness This enables additional checks that our code must pass at compile time before the interpreter will execute it. This is almost always a good thing to do. strict modes: vars, refs, and subs.Warnings and Strictness
  • 12.
    The crypt functionperforms a one-way transform of the string passed; it is identical to (and implemented using) the C library crypt on Unix systems, which implements a variation of the Data Encryption Standard (DES) algorithm.@characters = (0..9, 'a'..'z' ,'A'..'Z', '.', '/');$encrypted = crypt($password, @characters[rand 64, rand 64]);Password Encryption: crypt
  • 13.
    # check passworddie"Wrong!" unless crypt($entered, $encrypted) eq $encrypted;crypt – cont’d
  • 19.
    $good_egg = "Humpty". "Dumpty"; # produces "HumptyDumpty“"abc" x 3; # produces 'abcabcabc'String and List Operators
  • 20.
    Number of elementsin an array using scalar $count = scalar(@array); Last index in an array using $#$highest = $#array; # $highest = scalar(@array)-1Append an element to the array$array[scalar(@array)] push @arrayInsert at the beginningunshift @arrayTruncating and resizing@array = @array[0..3];Array Manipulation
  • 21.
    first: Return thefirst element of the list for which a condition is true.max, min: Return the highest and lowest numerical value, respectively.maxstr, minstr: Return the highest and lowest alphabetical value, respectively.sum: Return the sum of the list evaluated numerically.shuffle: Return the list in a random order.reduce: Reduce a list to a single value by arbitrary criteria.Array Manipulation - cont’d
  • 22.
    Use <STDIN> toreceive the input from the user.Keyboard Handling
  • 23.
    Example 1 #!/usr/bin/perl 2 # Fig. 2.17:fig02_17.pl 3 # Using if statements with relational and equality operators 4 5 print "Please enter first integer: "; 6 $number1 = <STDIN>; 7 chomp $number1; 8 9 print "Please enter second integer: "; 10 $number2 = <STDIN>; 11 chomp $number2; 12 13 print "The integers satisfy these relationships:\n"; 14 15 if ( $number1 == $number2 ) { 16 print "$number1 is equal to $number2.\n"; 17 } 18 19 if ( $number1 != $number2 ) { 20 print "$number1 is not equal to $number2.\n"; 21 } 22 23 if ( $number1 < $number2 ) { 24 print "$number1 is less than $number2.\n"; 25 } 26 27 if ( $number1 > $number2 ) { 28 print "$number1 is greater than $number2.\n"; 29 } 30
  • 24.
    Array Looping Example 1 #!/usr/bin/perl 2 #Fig. 4.3: fig04_03.pl 3 # Looping through an array with the for repetition structure. 4 5 @array = ( "Hello", 283, "there", 16.439 ); 6 7 # display every element of the array 8 for ( $i = 0; $i < 4; ++$i ) { 9 print "$i $array[ $i ]\n"; 10 }0 Hello1 2832 there3 16.439
  • 25.
  • 26.
  • 28.
    File Manipulation 1 #!usr/bin/perl 2 # Fig.10.6: fig10_06.pl 3 # Demonstrating writing to and reading from a file. 4 5 use strict; 6 use warnings; 7 8 print( "Opening file for output\n" ); 9 open( OUTFILE, ">file.txt" ) 10 or die( "Can't find file.txt : $!" ); 11 print( "Outputting to file\n" ); 12 print( OUTFILE "There was an old lady\n" ); 13 close( OUTFILE ) or die( "Can not close file.txt: $!" ); 14 15 print "The file now contains:\n"; 16 open( INFILE, "file.txt" ) 17 or die( "Can not open file.txt: $!" ); 18 print while ( <INFILE> ); 19 close( INFILE ) or die( "Can not close file.txt: $!" ); 20 21 print( "\nAppend to the end of the file\n" ); 22 open( OUTFILE, ">>file.txt" ) 23 or die( "Can not open file.txt: $!" ); 24 print( OUTFILE "who lived in a shoe.\n" ); 25 close( OUTFILE ) or die( "Can not close file.txt: $!" ); 26 27 print( "It now reads:\n" );
  • 29.
    28 open( INFILE, "file.txt") 29 or die( "Can not open file.txt: $!" ); 30 print while ( <INFILE> ); 31 close( INFILE ) or die( "Can not close file.txt: $!" );Opening file for outputOutputting to fileThe file now contains:There was an old lady Append to the end of the fileIt now reads:There was an old ladywho lived in a shoe.
  • 30.
    Exclusive Locking Example 1 #!/usr/bin/perl 2 #Fig. 10.11: fig10_11.pl 3 # Logs visitors to web site. 4 5 use strict; 6 use warnings; 7 use CGI qw( :standard ); 8 use Fcntl qw( :flock ); 9 10 my @vars = 11 qw( REMOTE_ADDR REMOTE_PORT REQUEST_URI QUERY_STRING ); 12 my @stuff = @ENV{ @vars }; 13 my $info = join( " | ", @stuff ); 14 15 open( FILE, "+>>log.txt" ) 16 or die( "Could not open log.txt: $!" ); 17 flock( FILE, LOCK_EX ) 18 or die( "Could not get exclusive lock: $!" ); 19 print( FILE "$info\n\n" ); 20 flock( FILE, LOCK_UN ) or die( "Could not unlock file: $!" ); 21 22 close( FILE ); 23 24 if ( $stuff[3] ne "" ) { 25 print( header( -Refresh=> '5; URL=http://www.google.com' ) ); 26 print( start_html( "log.txt" ) ); 27 print( h1( "Welcome to Deitel & Associates, $stuff[3]!\n" ) ); 28 print( p( i( "You will now be redirected to our home page." ) ) ); 29 }
  • 31.
    The @ARGV arraycontains all the arguments that were passed to our program when it was started. The definition of what defines an “argument” depends not on Perl, but on the shell that was used to start our program. However, in most cases spaces separate arguments from one another.The @ARGV Array
  • 32.
    perlmyscript -u sventek-p cuckooExample
  • 33.
    # number ofarguments passed scalar(@ARGV); # highest element = no. of arguments -1 $#ARGV;
  • 34.
    1 #!/usr/bin/perl 2 # Fig. 11.2:fig11_02.pl 3 # A program that uses file tests 4 5 use strict; 6 use warnings; 7 8 foreachmy $file ( @ARGV ) { 9 print( "Checking $file: " ); 10 11 if ( -e $file ) { # does file exist? 12 print( "$file exists!\n" ); 13 14 if ( -f $file ) { # is the file a plain file? 15 print( "The file $file is:" ); 16 print( " executable" ) if ( -x $file ); # executable? 17 print( " readable" ) if ( -r $file ); # readable? 18 print( " writable" ) if ( -w $file ); # writable? 19 print( "\n" ); 20 print( "It is ", -s $file, " bytes.\n" ); # size 21 my @time = timeconv( -A $file ); # accessed 22 print( "Last accessed at $time[0] days, ", 23 "$time[1] hours, $time[2] minutes ", 24 "and $time[3] seconds.\n" ); 25 @time = timeconv( -M $file ); # modified 26 print( "Last modified at $time[0] days, ", 27 "$time[1] hours, $time[2] minutes, ", 28 "and $time[3] seconds ago.\n" ); 29 }
  • 35.
    2 ways forconcurrencyProcessEach task has its own separate memory spaceLess portableMultithreadingUse the same memory processThe race conditionThe timing of threadsSynchronizationNot possible with processesEach knows when its data area is manipulatedProcess Management
  • 36.
    ways to forkCallthe systems fork commandNot always availableForkParent processCalls the fork functionChild processCreated by the fork functionEach has a process id or pidParent returns child pid and undef if unsuccessfulChild returns 0The fork command
  • 37.
    1 #!/usr/bin/perl 2 # Fig. 18.1:fig18_01.pl 3 # Using fork to create child processes. 4 5 use warnings; 6 use strict; 7 8 my ( $start, $middle, $end, $pid ); 9 $| = 1; 10 11 $start = time(); 12 A call is made to the fork function cloning the current process13if ( $pid = fork() ) { 14 sleep( 1 ); 15 print( "Parent executing.\n" ); 16 sleep( 2 ); 17 print( "Parent finished.\n" ); 18 }19elsif ( defined( $pid ) ) {Executes in the child process 20 sleep( 1 ); 21 print( "Child executing.\n" );22 sleep( 2 );Sleep is used to slow the program down 23 print( "Child finished.\n" ); 24 exit(); 25 } 26 else { 27 die( "Could not fork" ); 28 } 29
  • 38.
    30 $middle = time(); 31 32 print("That took " ); 33 print( $middle - $start );The time is used to compare using a process and not 34 print( " seconds with fork.\n" ); 35 36 sleep( 3 ); 37 sleep( 3 );38$end = time(); 39 40 print( "That took " ); 41 print( $end - $middle ); 42 print( " seconds without fork.\n" ); 43 print( "Total of ", ( $end - $start ), " seconds.\n" );Parent executing.Child executing.Parent finished.Child finished.That took 3 seconds with fork.That took 6 seconds without fork.Total of 9 seconds.
  • 39.
    1 #!/usr/bin/perl 2 # Fig. 18.2:fig18_02.pl 3 # Demonstrates the wait function. 4 5 use warnings; 6 use strict; 7 8 my ( $pid, $pid2 ); 9 $| = 1; 10 Create two forks for a total of three processes11if ( ( $pid = fork() ) && ( $pid2 = fork() ) ) { 12 print( "I have to wait for my kids.\n" ); 13 my $straggler = wait();14 print( "Finally $straggler finished, now I can go.\n" ); 15 }16elsif ( $pid && defined( $pid2 ) ) {Will not print until all the children are done 17 sleep( 2 ); 18 print( "Kid 2: So is mine...\n" ); 19 sleep( 4 ); 20 exit();Child 1 21 }22elsif ( defined( $pid ) ) { 23 sleep( 1 );Child 2 24 print( "Kid 1: My parent is patient...\n" ); 25 sleep( 2 ); 26 } 27 else { 28 die( "Forking problems: " ); 29 }I have to wait for my kids.Kid 1: My parent is patient...Kid 2: So is mine...Finally 296 finished, now I can go.
  • 40.
    1 #!/usr/bin/perl 2 # Fig. 18.3:fig18_03.pl 3 # Demonstrating the waitpid function. 4 5 use warnings; 6 use strict; 7 8 my ( $pid, $pid2 ); 9 $| = 1; 10 Since two fork methods are called then there will be 3 processes11if ( ( $pid = fork() ) && ( $pid2 = fork() ) ) { 12 print( "I have to wait for my kids.\n" );13my $straggler = waitpid( $pid, 0 ); 14 print( "Finally $straggler finished, now I can go.\n" ); 15 } 16 elsif ( $pid && defined( $pid2 ) ) {The waitpid function will cause the the third process to wait until the first process is finished 17 sleep( 2 ); 18 print( "Kid 2: Mine is not...\n" ); 19 sleep( 4 ); 20 print( "Kid 2: Hey! Wait for me!!!\n" ); 21 exit(); 22 } 23 elsif ( defined( $pid ) ) { 24 sleep( 1 ); 25 print( "Kid 1: My parent is patient...\n" ); 26 sleep( 2 ); 27 } 28 else { 29 die( "Forking problems: " ); 30 }
  • 41.
    I have towait for my kids.Kid 1: My parent is patient...Kid 2: Mine is not...Finally 269 finished, now I can go.Kid 2: Hey! Wait for me!!!
  • 42.
    The exec functionUsedto execute other programs from a programUses system shell to invoke a programNow program replaces current program’s processWhen new program terminates so does the old oneArguments passed is the program openedAll wild cards that work on the system are validIf a list is passedFirst is the programThe rest of the list is arguments to pass to that command without system processingThe system and exec functions
  • 43.
    The system functionSameas exec functionThe only difference is that the process is returned to the program when the opened program terminatesThis is done using a fork function and making one waitThe system and exec functions (II)
  • 44.
    1 #!/usr/bin/perl 2 # Fig. 18.4:fig18_04.pl 3 # Uses the system function to clear the screen. 4 5 use warnings; 6 use strict; 7 8 print( "What file would you like to create? " );Used to determine the OS that the program is running in. Will only work in Windows or when the command clear works 9 chomp( my $file = <STDIN> ); 10 11( $^O =~ /Win/ ) ? system( "cls" ) : system( "clear" ); 12 13 print( "Type the text you wish to be in this file.\n" ); 14 print( "Type clear on a blank line to start over.\n" ); 15 print( "Type quit on a blank line when you are finished.\n" ); 16 open( FILE, ">$file" ) or die( "Cannot open: $!" ); 17 Creates a loop that will continue until the user enters “quit” 18while ( <STDIN> ) { 19 lastif ( /quit/ ); 20 21 if ( /clear/ ) { 22 ( $^O =~ /Win/ ) ? system( "cls" ) : system( "clear" ); 23 print( "Type the text you wish to be in this file.\n" ); 24 print( "Type clear on a blank line to start over.\n" );Opens the file to write to 25 print( "Type quit on a blank line " ); 26 print( "when you are finished.\n" );27 open( FILE, ">$file" ) or die( "Cannot open: $!" ); 28 }
  • 45.
    29 else {Prints tothe file30 print( FILE ); 31 }Closes the file 32 } 33 34close( FILE ) or die( "Cannot close: $!" );What file would you like to create? hello.plType the text you wish to be in this file.Type clear on a blank line to start over.Type quit on a blank line when you are finished.#!/usr/bin/perl# hello.pl# Typical "hello world" program. use warnings;use strict; print( "Hello World" );quit
  • 46.
    1 #!/usr/bin/perl 2 # Fig. 18.6:fig18_06.pl 3 # Gets a web page and opens for editing. 4 5 use warnings;Will only open URLs that begin with http:// 6 use strict; 7 use LWP::Simple; 8 If the OS is windows then the program opens notepad, or else it will open vi 9 my( $URL, $filename ) = @ARGV;Uses the exec function to open the desired program and file 10 11if ( $URL !~ m#http://# ) { 12 $URL =~ s#^#http://#; 13 } 14 15 if ( is_error( getstore( $URL, $filename ) ) ) { 16 die( "Could not get file: $!" ); 17 } 18 19my $program = ( $^O =~ /Win/ ? "notepad.exe" : "vi" ); 20 21exec( $program, $filename );
  • 49.
    The open functionPlacesa pipe symbol (|) in the string that specifies the command to be executed.If at the front the input of a file is attached to a file handleIf at the end the output of a file is attached to a file handleWrite to the handle to modify the inputRead from the handle to modify the outputThe open2 functionAllows the use of both STDIN and STDOUTThe open3 functionAllows the programmer to obtain the STDERRControlling the Input and Output of Processes
  • 50.
    1 #!/usr/bin/perl 2 # Fig. 18.7:fig18_07.pl 3 # Demonstrating using open to connect different processes.Connects the STDOUT to the handle DIR 4 5 use warnings;Connects MORE to STDINWrites data to MORE 6 use strict; 7 Closes the pipes8open( DIR, "dir *.* |" ) or die( "Cannot open dir pipe: $!" );9open( MORE, "| more" ) or die( "Cannot open more: $!" ); 10 11 while ( <DIR> ) {12 print( MORE ); 13 } 14 15close( DIR ) or die( "Cannot close DIR: $!" ); 16 close( MORE ) or die( "Cannot close MORE: $!" );
  • 52.
    1 #!/usr/bin/perl 2 # Fig. 18.8:fig18_08.pl 3 # Demonstrates using backticks. 4 5 use warnings; 6 use strict; 7 8 my $date; 9 my $version; 10 If the operating system is Windows then display the version and the date11if ( $^O =~ /Win/ ) { 12 $version = ( `ver` ); 13 $date = ( `date /t` ); 14 }15else {If the OS is not Windows then use a different method to display its version and date 16 $version = ( `uname -r -s` ); 17 $date = ( `date` ); 18 } 19 20 print( "The Operating system version is $version"); 21 print( "\n", $date );The Operating system version is Microsoft Windows 2000 [Version 5.00.2195] Tue 11/28/2000 The Operating system version is Linux 2.2.14-6.1.1 Tue Nov 28 06:26:43 EST 2000
  • 53.
    1 #!/usr/bin/perl 2 # Fig. 18.9:fig18_09.pl 3 # Demonstrating the open2 function.Uses IPC::Open2 to allow for both input and output to be attached to a file handle 4 5 use warnings;Executes fig18_10.pl 6 use strict;7use IPC::Open2;Alters the output that fig18_10.pl would display 8 9 $| = 1; 10 my $command = 'perl fig18_10.pl'; 11 12open2( \*INPUT, \*OUTPUT, $command ) or 13 die( "Cannot open: $!" ); 14 15 for ( 1 .. 20 ) {16 print( OUTPUT $_, "\n" ); 17 my $read = <INPUT>; 18 print( $_, ' ', $read ); 19 } 20 21 close( OUTPUT ) or die( "Cannot close OUTPUT: $!" ); 22 close( INPUT ) or die( "Cannot close INPUT: $!" );
  • 54.
    1 MyItnkr.UtBnc2 My6jwfxg7zFGE3 My3G3DtIRpQEA4 Myza94uYasdEE5 MyCBteM4CIuTk6 MyWRtG.HnvdL27 Myb8qLeBJ6TlM8 MyE6k76L3NeoE9 MyxpYOghD0TIE10 MyI8Uhkz4HPjY11 MyB3G7m.CDII612 MyugXM4mJTc1c13 My9OUTHS6M.jg14 My8UYE/LL8dgU15 MyYAcz4F1r.to16 MycPbNadoaNYo17 MyXdTeyyclDNY18 MyTm8RxjwtKO.19 My2Q98KujB0i620 MyecGYzUxpdvk
  • 55.
    1 #!/usr/bin/perl 2 # Fig. 18.10:fig18_10.pl 3 # Helper to fig18_09.pl. 4 5 use warnings; 6 use strict; 7 8 $| = 1; 9 10 while ( <STDIN> ) {11 print( crypt( $_, "My cats' breath smells like cat food“ )); 12 print( "\n" ); 13 }A simple program the displays this line for output after being encrypted
  • 56.
    The pipe functionUsedto connect file handles of parent and children programsAllows them to communicate to each otherShould set $| to flush after each outputHelps to prevent deadlockUsing open with filename “-”Returns a handle that is a duplicate of STDIN or STDOUTCommunicating Between Processes
  • 57.
    1 #!/usr/bin/perl 2 # Fig. 18.11:fig18_11.pl 3 # Using pipe to communicate with child processes. 4 5 use warnings; 6 use strict; 7 use IO::Handle; 8 Links the parent input with the child output, and visa versa9pipe( CHILDINPUT, PARENTOUTPUT ); 10 pipe( PARENTINPUT, CHILDOUTPUT ); 11 12 PARENTOUTPUT->autoflush( 1 ); 13 CHILDOUTPUT->autoflush( 1 ); 14 STDOUT->autoflush( 1 ); 15 16if ( my $pid = fork() ) {Forks the program 17 18for ( 1 .. 10 ) {Loops ten times displaying its output and the child’s output 19 print( PARENTOUTPUT "$_\n" ); 20 print( "I said $_, " ); 21 chomp( my $response = <PARENTINPUT> ); 22 print( "and he said $response!\n" ); 23 } 24 25 close( PARENTOUTPUT ) orCloses the parent input and output handles 26 die( "Cannot close PARENTOUTPUT: $!" ); 27 close( PARENTINPUT ) or 28 die( "Cannot close PARENTINPUT: $!" ); 29 }
  • 58.
    The child code30elsif( defined( $pid ) ) {31 close( PARENTOUTPUT ) orCloses the parent input and output 32 die( "Cannot close PARENTOUTPUT: $!" ); 33 close( PARENTINPUT ) or 34 die( "Cannot close PARENTINPUT: $!" ); 35 36while ( <CHILDINPUT> ) {Prints out the parent output multiplied by 20 37 chomp(); 38 print( CHILDOUTPUT $_ * 20, "\n" ); 39 } 40 41 close( CHILDOUTPUT ) orCloses the child input and output 42 die( "Cannot close CHILDOUTPUT: $!" ); 43 close( CHILDINPUT ) or 44 die( "Cannot close CHILDINPUT: $!" ); 45 exit(); 46 } 47 else { 48 die( "Fork did not work" ); 49 } 50 51 print( "And that is the end of the conversation.\n" );I said 1, and he said 20!I said 2, and he said 40!I said 3, and he said 60!I said 4, and he said 80!I said 5, and he said 100!I said 6, and he said 120!I said 7, and he said 140!I said 8, and he said 160!I said 9, and he said 180!I said 10, and he said 200!And that is the end of the conversation.
  • 59.
    1 #!/usr/bin/perl 2 # Fig. 18.12:fig18_12.pl 3 # Using open to fork and filter output. 4 5 use warnings; 6 use strict; 7 8 $| = 1; 9 This will create a copy of the input in a file handle10if ( my $pid = open( CHILD, "-|" ) ) { 11 my $i; 12 Displays the line number13while ( <CHILD> ) { 14 print( "Line ", ++$i, ": $_" ); 15 } 16 17 close( CHILD ) or die( "Cannot close: $!" ); 18 }Will output the lines synchronized with the line number output19elsif ( defined( $pid ) ) { 20 print( "I am doing some\n" ); 21 print( "processing here\n" ); 22 print( "that produces\n" ); 23 print( "multiple lines\n" ); 24 print( "of output.\n" ); 25 exit(); 26 } 27 else { 28 print( "Could not fork." ); 29 }Line 1: I am doing someLine 2: processing hereLine 3: that producesLine 4: multiple linesLine 5: of output.
  • 60.
    SignalsMessages that aredelivered to a program by the OSAllow processes to communicate with one anotherSignals are generated by several thingsErrorsEventsUser inputInternally from a programMost signals can be overriddenSIGKILL and SIGSTOP cannot be overriddenUsed as a last resort for programs that stop respondingSignals Handling
  • 61.
    Special Signals__DIE__ (twounderscores (_))Used to override the die commandNot effective when first invokedPrevents infinite recursion__WARN__Used to override the warn commandDEFAULTReturns a signal to its original stateIGNOREIgnores a signalSignals Handling (II)
  • 62.
  • 63.
    1 #!/usr/bin/perl 2 # Fig. 18.14:fig18_14.pl 3 # Demonstrates using %SIG to define our own signal handlers. 4 5 use warnings;Every time SIGINT is used it calls the stop function 6 use strict;Prints out Hooray! every second as long as $count does not equal zero 7 8 my $count = 3;Subtracts one from the counter and displays it 9 $| = 1; 10 11$SIG{ 'INT' } = \&stop; 12 13while ( $count ) { 14 print( "Hooray!" ); 15 print( "\n" ); 16 sleep( 1 ); 17 } 18 19 sub stop 20 { 21 $SIG{ 'INT' } = \&stop;22 $count--; 23 print( "$count\n" ); 24 25 unless ( $count ) { 26 print( "Sorry, I did not want to stop...\n" ); 27 } 28 }
  • 64.
  • 65.
    The kill functionUsedto send signals to another processFirst argument is the signal to be sentRest of the arguments are the processes to send the signal toTerminating childrenLeave behind zombies in process tableAllow parent to figure out if the child ended normallyReaping is performed to eliminate zombiesUse the wait or waitpid functions to do additional operationsThe IGNORE statement is used to remove the children from the tableSending Signals
  • 66.
    1 #!/usr/bin/perl 2 # Fig. 18.15:fig18_15.pl 3 # Sending signals to child processes using kill. 4 5 use warnings; 6 use strict; 7 use POSIX qw( :signal_h :errno_h :sys_wait_h ); 8 9$SIG{ USR1 } = \&user1;Calls the desired functions 10 $SIG{ USR2 } = \&user2; 11 $| = 1; 12 13 sub user1 14 { 15 $SIG{ USR1 } = \&user1;Displays when the signal is received16 print( "I have received SIGUSR1.\n" ); 17 } 18 19 sub user2 20 { 21 $SIG{ USR2 } = \&user2; 22 print( "I have received SIGUSR2.\n" ); 23 } 24
  • 67.
    25 if ( my$pid = fork() ) {Sends a signal using the kill function26 kill( 'USR1', $pid ); 27 kill( 'USR2', $pid ); 28 print( "I have just sent two signals.\n" ); 29 sleep( 2 ); 30 print( "Now I am going to send a few more.\n" ); 31 kill( USR2 => $pid ); 32 kill( USR1 => $pid ); 33 print( "Parent done.\n" ); 34 } 35 elsif ( defined( $pid ) ) { 36 sleep( 5 ); 37 print( "Kid done.\n" ); 38 exit(); 39 } 40 else { 41 print( "Forking error...\n" ); 42 } 43 44 wait();fig18_15.plProgram OutputI have just sent two signals.I have received SIGUSR2.I have received SIGUSR1.Now I am going to send a few more.Parent done.I have received SIGUSR2.I have received SIGUSR1.Kid done.
  • 68.
    Install new port.Mountingand Unmounting File SystemsConfigure interface.Soft/Hard Linking.FreeBSD Administration
  • 69.
    Adding Packagespkg_add -rlsof-4.56.4Deleting Packagespkg_delete xchat-1.7.1Packages
  • 70.
    Makefile: The Makefile contains variousstatements that specify how the application should be compiled and where it should be installed on your systemdistinfo file: This file contains information about the files that must be downloaded to build the port, and checksums, to ensure that those files have not been corrupted during the download.files directory: This directory contains patches to make the program compile and install on your FreeBSD system. This directory may also contain other files used in building the port.pkg-comment file: This is a one-line description of the program.pkg-descr file: This is a more detailed, often multiple-line, description of the program.pkg-plist file: This is a list of all the files that will be installed by the port. It also tells the ports system what files to remove upon deinstallation.Port Installation
  • 71.
    # whereislsoflsof/usr/ports/sysutils/lsofNote: You mustbe the root user to install ports.# cd /usr/ports/sysutils/lsofExample
  • 72.
    make>> lsof_4.57D.freebsd.tar.gz doesn'tseem to exist in /usr/ports/distfiles/. >> Attempting to fetch from file:/cdrom/ports/distfiles/.===> Extracting for lsof-4.57 ... [extraction output snipped] ... >> Checksum OK for lsof_4.57D.freebsd.tar.gz. ===> Patching for lsof-4.57 ===> Applying FreeBSD patches for lsof-4.57 ===> Configuring for lsof-4.57 ... [configure output snipped] ... ===> Building for lsof-4.57 ... [compilation snipped] ... #
  • 73.
    # make install===>Installing for lsof-4.57 ... [install routines snipped] ... ===> Generating temporary packing list ===> Compressing manual pages for lsof-4.57 ===> Registering installation for lsof-4.57===> SECURITY NOTE: This port has installed the following binaries which execute with increased privileges.
  • 74.
    # cd /usr/ports/irc/lsof#make deinstall===> Deinstalling for lsof-4.57 Removing Installed Ports
  • 75.
    /etc/fstab FileThe /etc/fstab file contains alist of lines of the following format: device /mount-point fstype options dumpfreqpassnmount-point: directory on which to mount the file system.fstype: The file system type to pass to mount. The default FreeBSD file system is ufs.Options: Either rw for read-write file systems, or ro for read-only file systems, followed by any other options that may be needed. A common option is noauto for file systems not normally mounted during the boot sequence. dumpfreq: This is used by dump to determine which file systems require dumping. If the field is missing, a value of zero is assumed.passno: This determines the order in which file systems should be checked. Mounting and Unmounting File Systems
  • 76.
    In its mostbasic form, you use: # mount devicemountpoint-a Mount all the file systems listed in /etc/fstab. Except those marked as “noauto”, excluded by the -t flag, or those that are already mounted.-d Do everything except for the actual mount system call. This option is useful in conjunction with the -v flag to determine what mount is actually trying to do.-f Force the mount of an unclean file system (dangerous), or forces the revocation of write access when downgrading a file system's mount status from read-write to read-only.-r Mount the file system read-only. This is identical to using the ro argument to the -o option.The mount command
  • 77.
    Through sysinstall ->configure -> Networking -> InterfacesUse ifconfig command as follows:ifconfig interface inet IP Example:ifconfiglnc0 inet 202.54.1.22Notes: To setup up ip permanently open file /etc/rc.conf ; add/modify network entries:ee/etc/rc.conf
  • 78.
    Setup valuesas follows:hostname="fbsdx.test.com"ifconfig_lnc0="inet 192.168.0.6 netmask 255.255.255.0"
  • 79.
    Ethernet interface namecan be Obtained using ifconfig -a command.
  • 80.
    You should run/etc/netstartscript or /etc/rc.d/netif restart.Interface Configuration
  • 81.
    a hard linkis a pointer to the file's i-node. a soft link, also called symbolic link, is a file that contains the name of another file. We can then access the contents of the other file through that name. That is, a symbolic link is like a pointer to the pointer to the file's contents.Hard Links Vs. Soft Links
  • 82.
    Pointers to programs,files, or directories located elsewhere (just like Windows shortcuts)
  • 83.
    If the originalprogram, file, or directory is renamed, moved, or deleted, the soft link is broken. 
  • 84.
    If you type ls-F you can see which files are soft links because they end with @
  • 85.
    To create asoft link called myfilelink.txt that points to a file called myfile.txt, use this: ln-s myfile.txt myfilelink.txtSoft links
  • 86.
    Pointers to programsand files, but NOT directories
  • 87.
    If the originalprogram or file is renamed, moved, or deleted, the hard link is NOT broken
  • 88.
    Hard links cannotspan disk drives, so you CANNOT have a hard link on /dev/hdb that refers to a program or file on /dev/had
  • 89.
    Can’t connect filesfrom different file systems.
  • 90.
    To create ahard link called myhardlink.txt that points to a file called myfile.txt, use this: ln myfile.txt myhardlink.txtHard links
  • 91.
  • 92.
  • 93.
  • 94.