SlideShare a Scribd company logo
1 of 84
Mohammed Farragmfarrag@freebsd.orghttp://wiki.freebsd.org/MohammedFarrag
Perl Programming Language. FreeBSD Administration Overview
Every UNIX program in Perl should start with #!/usr/bin/perl Every 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";    } 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 password die "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)-1 Append an element to the array $array[scalar(@array)]  push @array Insert at the beginning unshift @array Truncating 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:"; 	14	 	15	if ( $number1 == $number2 ) { 	16	   print "$number1 is equal to $number2."; 	17	} 	18	 	19	if ( $number1 != $number2 ) { 	20	   print "$number1 is not equal to $number2."; 	21	} 	22	 	23	if ( $number1 < $number2 ) { 	24	   print "$number1 is less than $number2."; 	25	} 	26	 	27	if ( $number1 > $number2 ) { 	28	   print "$number1 is greater than $number2."; 	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 ]"; 	10	} 0   Hello 1   283 2   there 3   16.439
Data Hierarchy Sally Black Tom Blue File Judy Green Iris Orange Randy Red Record Judy Green Field J u d y Byte (ASCII character J) 01001010 Bit 1
Open Seek Truncate Print close File 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" ); 	9	open( OUTFILE, ">file.txt" )  	10	or die( "Can't find file.txt : $!" ); 	11	print( "Outputting to file" ); 	12	print( OUTFILE "There was an old lady" ); 	13	close( OUTFILE ) or die( "Can not close file.txt: $!" ); 	14	 	15	print "The file now contains:"; 	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( "Append to the end of the file" ); 	22	open( OUTFILE, ">>file.txt" )  	23	or die( "Can not open file.txt: $!" ); 	24	print( OUTFILE "who lived in a shoe." ); 	25	close( OUTFILE ) or die( "Can not close file.txt: $!" ); 	26	 	27	print( "It now reads:" );
	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 output Outputting to file The file now contains: There was an old lady   Append to the end of the file It now reads: There was an old lady who 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" ); 	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]!" ) ); 	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 cuckoo Example
# 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!" ); 	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( "" ); 	20	         print( "It is ", -s $file, " bytes." ); # 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." ); 	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." ); 	29	      }
2 ways for concurrency Process Each task has its own separate memory space Less portable Multithreading Use the same memory process The race condition The timing of threads Synchronization Not possible with processes Each knows when its data area is manipulated Process Management
ways to fork Call the systems fork command Not always available Fork Parent process Calls the fork function Child process Created by the fork function Each has a process id or pid Parent returns child pid and undef if unsuccessful Child returns 0 The 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 process 13if ( $pid = fork() ) { 	14	   sleep( 1 ); 	15	   print( "Parent executing." ); 	16	   sleep( 2 ); 	17	   print( "Parent finished." ); 	18	} 19elsif ( defined( $pid ) ) { Executes in the child process 	20	   sleep( 1 ); 	21	   print( "Child executing." ); 22   sleep( 2 ); Sleep is used to slow the program down 	23	   print( "Child finished." ); 	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." ); 	35	 	36	sleep( 3 ); 	37	sleep( 3 ); 38$end = time(); 	39	 	40	print( "That took " ); 	41	print( $end - $middle ); 	42	print( " seconds without fork." ); 	43	print( "Total of ", ( $end - $start ), " seconds." ); 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 processes 11if ( ( $pid = fork() ) && ( $pid2 = fork() ) ) { 	12	   print( "I have to wait for my kids." ); 	13	my $straggler = wait(); 14   print( "Finally $straggler finished, now I can go." ); 	15	} 16elsif ( $pid && defined( $pid2 ) ) { Will not print until all the children are done 	17	   sleep( 2 ); 	18	   print( "Kid 2: So is mine..." ); 	19	   sleep( 4 ); 	20	   exit(); Child 1 	21	} 22elsif ( defined( $pid ) ) { 	23	   sleep( 1 ); Child 2 	24	   print( "Kid 1: My parent is patient..." ); 	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 processes 11if ( ( $pid = fork() ) && ( $pid2 = fork() ) ) { 	12	   print( "I have to wait for my kids." ); 13my $straggler = waitpid( $pid, 0 ); 	14	   print( "Finally $straggler finished, now I can go." ); 	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..." ); 	19	   sleep( 4 ); 	20	   print( "Kid 2: Hey! Wait for me!!!" ); 	21	   exit(); 	22	} 	23	elsif ( defined( $pid ) ) { 	24	   sleep( 1 ); 	25	   print( "Kid 1: My parent is patient..." ); 	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 function Used to execute other programs from a program Uses system shell to invoke a program Now program replaces current program’s process When new program terminates so does the old one Arguments passed is the program opened All wild cards that work on the system are valid If a list is passed First is the program The rest of the list is arguments to pass to that command without system processing The system and exec functions
The system function Same as exec function The only difference is that the process is returned to the program when the opened program terminates This is done using a fork function and making one wait The 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." ); 	14	print( "Type clear on a blank line to start over." ); 	15	print( "Type quit on a blank line when you are finished." ); 	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." ); 	24	      print( "Type clear on a blank line to start over." ); Opens the file to write to 	25	      print( "Type quit on a blank line " ); 	26	      print( "when you are finished." ); 27      open( FILE, ">$file" ) or die( "Cannot open: $!" ); 	28	   }
	29	else { Prints to the file 30      print( FILE ); 	31	   } Closes the file 	32	} 	33	 34close( FILE ) or die( "Cannot close: $!" ); What file would you like to create? hello.pl Type 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 function Places 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 handle If at the end the output of a file is attached to a file handle Write to the handle to modify the input Read from the handle to modify the output The open2 function Allows the use of both STDIN and STDOUT The open3 function Allows the programmer to obtain the STDERR Controlling 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 STDIN Writes data to MORE 	6	use strict; 	7	 Closes the pipes 8open( 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 date 11if ( $^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( "", $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 $_, "" ); 	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.UtBnc 2  My6jwfxg7zFGE 3  My3G3DtIRpQEA 4  Myza94uYasdEE 5  MyCBteM4CIuTk 6  MyWRtG.HnvdL2 7  Myb8qLeBJ6TlM 8  MyE6k76L3NeoE 9  MyxpYOghD0TIE 10  MyI8Uhkz4HPjY 11  MyB3G7m.CDII6 12  MyugXM4mJTc1c 13  My9OUTHS6M.jg 14  My8UYE/LL8dgU 15  MyYAcz4F1r.to 16  MycPbNadoaNYo 17  MyXdTeyyclDNY 18  MyTm8RxjwtKO. 19  My2Q98KujB0i6 20  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( "" ); 	13	} A simple program the displays this line for output after being encrypted
The pipe function Used to connect file handles of parent and children programs Allows them to communicate to each other Should set $| to flush after each output Helps to prevent deadlock Using open with filename “-” Returns a handle that is a duplicate of STDIN or STDOUT Communicating 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 versa 9pipe( 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 "$_" ); 	20	      print( "I said $_, " ); 	21	      chomp( my $response = <PARENTINPUT> ); 	22	      print( "and he said $response!" ); 	23	   } 	24	 25   close( PARENTOUTPUT ) or Closes the parent input and output handles 	26	      die( "Cannot close PARENTOUTPUT: $!" ); 	27	   close( PARENTINPUT ) or 	28	      die( "Cannot close PARENTINPUT: $!" ); 	29	}
The child code 30elsif ( defined( $pid ) ) { 31   close( PARENTOUTPUT ) or Closes 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, "" ); 	39	   } 	40	 41   close( CHILDOUTPUT ) or Closes 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." ); 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 handle 10if ( my $pid = open( CHILD, "-|" ) ) { 	11	my $i; 	12	 Displays the line number 13while ( <CHILD> ) { 	14	      print( "Line ", ++$i, ": $_" ); 	15	   } 	16	 	17	   close( CHILD ) or die( "Cannot close: $!" ); 	18	} Will output the lines synchronized with the line number output 19elsif ( defined( $pid ) ) { 	20	   print( "I am doing some" ); 	21	   print( "processing here" ); 	22	   print( "that produces" ); 	23	   print( "multiple lines" ); 	24	   print( "of output." ); 	25	   exit(); 	26	} 	27	else { 	28	   print( "Could not fork." ); 	29	} Line 1: I am doing some Line 2: processing here Line 3: that produces Line 4: multiple lines Line 5: of output.
Signals Messages that are delivered to a program by the OS Allow processes to communicate with one another Signals are generated by several things Errors Events User input Internally from a program Most signals can be overridden SIGKILL and SIGSTOP cannot be overridden Used as a last resort for programs that stop responding Signals Handling
Special Signals __DIE__ (two underscores (_)) Used to override the die command Not effective when first invoked Prevents infinite recursion __WARN__ Used to override the warn command DEFAULT Returns a signal to its original state IGNORE Ignores a signal Signals 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' } = amp;stop; 	12	 13while ( $count ) { 	14	   print( "Hooray!" ); 	15	   print( "" ); 	16	   sleep( 1 ); 	17	} 	18	 	19	sub stop 	20	{ 	21	   $SIG{ 'INT' } = amp;stop; 22   $count--; 	23	   print( "$count" ); 	24	 	25	unless ( $count ) { 	26	      print( "Sorry, I did not want to stop..." ); 	27	   } 	28	}
Hooray! Hooray! 2 Hooray! Hooray! Hooray! 1 Hooray! 0 Sorry, I did not want to stop...
The kill function Used to send signals to another process First argument is the signal to be sent Rest of the arguments are the processes to send the signal to Terminating children Leave behind zombies in process table Allow parent to figure out if the child ended normally Reaping is performed to eliminate zombies Use the wait or waitpid functions to do additional operations The IGNORE statement is used to remove the children from the table Sending 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 } = amp;user1; Calls the desired functions 	10	$SIG{ USR2 } = amp;user2; 	11	$| = 1; 	12	 	13	sub user1  	14	{ 	15	   $SIG{ USR1 } = amp;user1; Displays when the signal is received 16   print( "I have received SIGUSR1." ); 	17	} 	18	 	19	sub user2  	20	{ 	21	   $SIG{ USR2 } = amp;user2; 	22	   print( "I have received SIGUSR2." ); 	23	} 	24
	25	if ( my $pid = fork() ) { Sends a signal using the kill function 26   kill( 'USR1', $pid ); 	27	   kill( 'USR2', $pid ); 	28	   print( "I have just sent two signals." ); 	29	   sleep( 2 ); 	30	   print( "Now I am going to send a few more." ); 	31	   kill( USR2 => $pid ); 	32	   kill( USR1 => $pid ); 	33	   print( "Parent done." ); 	34	} 	35	elsif ( defined( $pid ) ) { 	36	   sleep( 5 ); 	37	   print( "Kid done." ); 	38	   exit(); 	39	} 	40	else { 	41	   print( "Forking error..." ); 	42	} 	43	 	44	wait(); fig18_15.pl Program Output I 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 Systems Configure interface. Soft/Hard Linking. FreeBSD Administration
Adding Packages pkg_add -r lsof-4.56.4 Deleting Packages pkg_delete xchat-1.7.1 Packages
Makefile: The Makefile contains various statements that specify how the application should be compiled and where it should be installed on your system distinfo 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
[object Object],/usr/ports/sysutils/lsof Note: You must be the root user to install ports. ,[object Object],Example
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 File The /etc/fstab file contains a list of lines of the following format:    device     /mount-point fstype       options    dumpfreqpassn mount-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 -> Interfaces Use ifconfig command as follows:ifconfig interface inet IP          Example:ifconfiglnc0 inet 202.54.1.22 Notes:  ,[object Object]
 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
[object Object]
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 @

More Related Content

What's hot

도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템
도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템
도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템Sam Kim
 
Talk 160920 @ Cat System Workshop
Talk 160920 @ Cat System WorkshopTalk 160920 @ Cat System Workshop
Talk 160920 @ Cat System WorkshopQuey-Liang Kao
 
Fun with Network Interfaces
Fun with Network InterfacesFun with Network Interfaces
Fun with Network InterfacesKernel TLV
 
grsecurity and PaX
grsecurity and PaXgrsecurity and PaX
grsecurity and PaXKernel TLV
 
Linux fundamental - Chap 09 pkg
Linux fundamental - Chap 09 pkgLinux fundamental - Chap 09 pkg
Linux fundamental - Chap 09 pkgKenny (netman)
 
Building Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCCBuilding Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCCKernel TLV
 
Linux Containers From Scratch: Makfile MicroVPS
Linux Containers From Scratch: Makfile MicroVPSLinux Containers From Scratch: Makfile MicroVPS
Linux Containers From Scratch: Makfile MicroVPSjoshuasoundcloud
 
Pursue container architecture with mincs
Pursue container architecture with mincsPursue container architecture with mincs
Pursue container architecture with mincsYuki Nishiwaki
 
Working with core dump
Working with core dumpWorking with core dump
Working with core dumpThierry Gayet
 
Unix Shell Script
Unix Shell ScriptUnix Shell Script
Unix Shell Scriptstudent
 
Linux Kernel Debugging Essentials workshop
Linux Kernel Debugging Essentials workshopLinux Kernel Debugging Essentials workshop
Linux Kernel Debugging Essentials workshopLubomir Rintel
 
Useful Linux and Unix commands handbook
Useful Linux and Unix commands handbookUseful Linux and Unix commands handbook
Useful Linux and Unix commands handbookWave Digitech
 
High Availability Server with DRBD in linux
High Availability Server with DRBD in linuxHigh Availability Server with DRBD in linux
High Availability Server with DRBD in linuxAli Rachman
 
Linux kernel debugging(ODP format)
Linux kernel debugging(ODP format)Linux kernel debugging(ODP format)
Linux kernel debugging(ODP format)yang firo
 

What's hot (20)

도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템
도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템
도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템
 
Talk 160920 @ Cat System Workshop
Talk 160920 @ Cat System WorkshopTalk 160920 @ Cat System Workshop
Talk 160920 @ Cat System Workshop
 
50 Most Frequently Used UNIX Linux Commands -hmftj
50 Most Frequently Used UNIX  Linux Commands -hmftj50 Most Frequently Used UNIX  Linux Commands -hmftj
50 Most Frequently Used UNIX Linux Commands -hmftj
 
50 most frequently used unix
50 most frequently used unix50 most frequently used unix
50 most frequently used unix
 
Fun with Network Interfaces
Fun with Network InterfacesFun with Network Interfaces
Fun with Network Interfaces
 
grsecurity and PaX
grsecurity and PaXgrsecurity and PaX
grsecurity and PaX
 
Putting some "logic" in LVM.
Putting some "logic" in LVM.Putting some "logic" in LVM.
Putting some "logic" in LVM.
 
Linux fundamental - Chap 09 pkg
Linux fundamental - Chap 09 pkgLinux fundamental - Chap 09 pkg
Linux fundamental - Chap 09 pkg
 
Building Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCCBuilding Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCC
 
Linux Containers From Scratch: Makfile MicroVPS
Linux Containers From Scratch: Makfile MicroVPSLinux Containers From Scratch: Makfile MicroVPS
Linux Containers From Scratch: Makfile MicroVPS
 
Pursue container architecture with mincs
Pursue container architecture with mincsPursue container architecture with mincs
Pursue container architecture with mincs
 
Fun with FUSE
Fun with FUSEFun with FUSE
Fun with FUSE
 
Working with core dump
Working with core dumpWorking with core dump
Working with core dump
 
Unix Shell Script
Unix Shell ScriptUnix Shell Script
Unix Shell Script
 
Linux Kernel Debugging Essentials workshop
Linux Kernel Debugging Essentials workshopLinux Kernel Debugging Essentials workshop
Linux Kernel Debugging Essentials workshop
 
Kernel crashdump
Kernel crashdumpKernel crashdump
Kernel crashdump
 
Useful Linux and Unix commands handbook
Useful Linux and Unix commands handbookUseful Linux and Unix commands handbook
Useful Linux and Unix commands handbook
 
High Availability Server with DRBD in linux
High Availability Server with DRBD in linuxHigh Availability Server with DRBD in linux
High Availability Server with DRBD in linux
 
Linux kernel debugging(ODP format)
Linux kernel debugging(ODP format)Linux kernel debugging(ODP format)
Linux kernel debugging(ODP format)
 
Linuxppt
LinuxpptLinuxppt
Linuxppt
 

Viewers also liked

Viewers also liked (20)

The practices, challenges and opportunities of board composition and leadersh...
The practices, challenges and opportunities of board composition and leadersh...The practices, challenges and opportunities of board composition and leadersh...
The practices, challenges and opportunities of board composition and leadersh...
 
Temple romà
Temple romàTemple romà
Temple romà
 
Presentation1
Presentation1Presentation1
Presentation1
 
Welcome to msp information night 2013
Welcome to msp information night 2013Welcome to msp information night 2013
Welcome to msp information night 2013
 
Inbooki
Inbooki Inbooki
Inbooki
 
Wikipedia: A Tool for Teaching (Skeptical) Research
Wikipedia: A Tool for Teaching (Skeptical) Research Wikipedia: A Tool for Teaching (Skeptical) Research
Wikipedia: A Tool for Teaching (Skeptical) Research
 
2 Thessalonians 2
2 Thessalonians 22 Thessalonians 2
2 Thessalonians 2
 
Gearman - Northeast PHP 2012
Gearman - Northeast PHP 2012Gearman - Northeast PHP 2012
Gearman - Northeast PHP 2012
 
第10-11週
第10-11週第10-11週
第10-11週
 
liceo paola cs
liceo paola csliceo paola cs
liceo paola cs
 
Book IV Getting The Internship You Want: How to write APPIC essays that get ...
Book IV Getting The Internship You Want:  How to write APPIC essays that get ...Book IV Getting The Internship You Want:  How to write APPIC essays that get ...
Book IV Getting The Internship You Want: How to write APPIC essays that get ...
 
Dg Analysis Haiti Earthquake 14 Jan2010
Dg Analysis Haiti Earthquake 14 Jan2010Dg Analysis Haiti Earthquake 14 Jan2010
Dg Analysis Haiti Earthquake 14 Jan2010
 
Sony Xperia V LT25i
Sony Xperia V LT25iSony Xperia V LT25i
Sony Xperia V LT25i
 
mediator2
mediator2mediator2
mediator2
 
Les 2 Informatieverzorging
Les 2 InformatieverzorgingLes 2 Informatieverzorging
Les 2 Informatieverzorging
 
Funny Images
Funny ImagesFunny Images
Funny Images
 
Aptso cosechas 2010
Aptso cosechas 2010Aptso cosechas 2010
Aptso cosechas 2010
 
Kenzy klauser vet speech and preso
Kenzy klauser vet speech and presoKenzy klauser vet speech and preso
Kenzy klauser vet speech and preso
 
Comparatives1
Comparatives1Comparatives1
Comparatives1
 
Answergen bi ppt-apr 09 2015
Answergen bi   ppt-apr 09 2015Answergen bi   ppt-apr 09 2015
Answergen bi ppt-apr 09 2015
 

Similar to Perl Programming Language File Handling and Testing

Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1Dave Cross
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to PerlDave Cross
 
Bioinformatica 29-09-2011-p1-introduction
Bioinformatica 29-09-2011-p1-introductionBioinformatica 29-09-2011-p1-introduction
Bioinformatica 29-09-2011-p1-introductionProf. Wim Van Criekinge
 
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...Andrea Telatin
 
You Can Do It! Start Using Perl to Handle Your Voyager Needs
You Can Do It! Start Using Perl to Handle Your Voyager NeedsYou Can Do It! Start Using Perl to Handle Your Voyager Needs
You Can Do It! Start Using Perl to Handle Your Voyager NeedsRoy Zimmer
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl TechniquesDave Cross
 
PERL for QA - Important Commands and applications
PERL for QA - Important Commands and applicationsPERL for QA - Important Commands and applications
PERL for QA - Important Commands and applicationsSunil Kumar Gunasekaran
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perlworr1244
 
Bioinformatics p4-io v2013-wim_vancriekinge
Bioinformatics p4-io v2013-wim_vancriekingeBioinformatics p4-io v2013-wim_vancriekinge
Bioinformatics p4-io v2013-wim_vancriekingeProf. Wim Van Criekinge
 
Shell Scripts
Shell ScriptsShell Scripts
Shell ScriptsDr.Ravi
 
Beginning Perl
Beginning PerlBeginning Perl
Beginning PerlDave Cross
 

Similar to Perl Programming Language File Handling and Testing (20)

Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Perl Basics with Examples
Perl Basics with ExamplesPerl Basics with Examples
Perl Basics with Examples
 
Perl slid
Perl slidPerl slid
Perl slid
 
Perl Presentation
Perl PresentationPerl Presentation
Perl Presentation
 
Bioinformatica 29-09-2011-p1-introduction
Bioinformatica 29-09-2011-p1-introductionBioinformatica 29-09-2011-p1-introduction
Bioinformatica 29-09-2011-p1-introduction
 
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
 
Shell programming
Shell programmingShell programming
Shell programming
 
Bioinformatica p4-io
Bioinformatica p4-ioBioinformatica p4-io
Bioinformatica p4-io
 
You Can Do It! Start Using Perl to Handle Your Voyager Needs
You Can Do It! Start Using Perl to Handle Your Voyager NeedsYou Can Do It! Start Using Perl to Handle Your Voyager Needs
You Can Do It! Start Using Perl to Handle Your Voyager Needs
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl Techniques
 
Hashes Master
Hashes MasterHashes Master
Hashes Master
 
Bioinformatica 27-10-2011-p4-files
Bioinformatica 27-10-2011-p4-filesBioinformatica 27-10-2011-p4-files
Bioinformatica 27-10-2011-p4-files
 
PERL for QA - Important Commands and applications
PERL for QA - Important Commands and applicationsPERL for QA - Important Commands and applications
PERL for QA - Important Commands and applications
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Bioinformatics p4-io v2013-wim_vancriekinge
Bioinformatics p4-io v2013-wim_vancriekingeBioinformatics p4-io v2013-wim_vancriekinge
Bioinformatics p4-io v2013-wim_vancriekinge
 
Shell Scripts
Shell ScriptsShell Scripts
Shell Scripts
 
Beginning Perl
Beginning PerlBeginning Perl
Beginning Perl
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 

More from Mohammed Farrag

Resume for Mohamed Farag
Resume for Mohamed FaragResume for Mohamed Farag
Resume for Mohamed FaragMohammed Farrag
 
Mum Article Recognition for Mohamed Farag
Mum Article Recognition for Mohamed FaragMum Article Recognition for Mohamed Farag
Mum Article Recognition for Mohamed FaragMohammed Farrag
 
Artificial Intelligence Programming in Art by Mohamed Farag
Artificial Intelligence Programming in Art by Mohamed FaragArtificial Intelligence Programming in Art by Mohamed Farag
Artificial Intelligence Programming in Art by Mohamed FaragMohammed Farrag
 
Confirmation letter info tech 2013(1)
Confirmation letter info tech 2013(1)Confirmation letter info tech 2013(1)
Confirmation letter info tech 2013(1)Mohammed Farrag
 
Lecture 5 Kernel Development
Lecture 5 Kernel DevelopmentLecture 5 Kernel Development
Lecture 5 Kernel DevelopmentMohammed Farrag
 

More from Mohammed Farrag (11)

Resume for Mohamed Farag
Resume for Mohamed FaragResume for Mohamed Farag
Resume for Mohamed Farag
 
Mum Article Recognition for Mohamed Farag
Mum Article Recognition for Mohamed FaragMum Article Recognition for Mohamed Farag
Mum Article Recognition for Mohamed Farag
 
Create 2015 Event
Create 2015 EventCreate 2015 Event
Create 2015 Event
 
Artificial Intelligence Programming in Art by Mohamed Farag
Artificial Intelligence Programming in Art by Mohamed FaragArtificial Intelligence Programming in Art by Mohamed Farag
Artificial Intelligence Programming in Art by Mohamed Farag
 
Confirmation letter info tech 2013(1)
Confirmation letter info tech 2013(1)Confirmation letter info tech 2013(1)
Confirmation letter info tech 2013(1)
 
[ArabBSD] Unix Basics
[ArabBSD] Unix Basics[ArabBSD] Unix Basics
[ArabBSD] Unix Basics
 
Google APPs and APIs
Google APPs and APIsGoogle APPs and APIs
Google APPs and APIs
 
Lecture 5 Kernel Development
Lecture 5 Kernel DevelopmentLecture 5 Kernel Development
Lecture 5 Kernel Development
 
FreeBSD Handbook
FreeBSD HandbookFreeBSD Handbook
FreeBSD Handbook
 
Master resume
Master resumeMaster resume
Master resume
 
Mohammed Farrag Resume
Mohammed Farrag ResumeMohammed Farrag Resume
Mohammed Farrag Resume
 

Recently uploaded

Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...DhatriParmar
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Developmentchesterberbo7
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxMichelleTuguinay1
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 

Recently uploaded (20)

Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Development
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
 
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 
Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 

Perl Programming Language File Handling and Testing

  • 2. Perl Programming Language. FreeBSD Administration Overview
  • 3. Every UNIX program in Perl should start with #!/usr/bin/perl Every 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 a number or string. Examples $scalarint = 42; $scalarfp = 1.01; $scalarstr = "A string is a scalar"; Scalars
  • 5. 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
  • 6. 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
  • 7. 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
  • 8.
  • 9. A subroutine is a block that is declared for reuse with the sub keyword. Examples sub red_october { print "A simple sub"; } To call this subroutine, we can now just write any of the following: red_october; &red_october; red_october(); Subroutine
  • 10. 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
  • 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 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
  • 13. # check password die "Wrong!" unless crypt($entered, $encrypted) eq $encrypted; crypt – cont’d
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19. $good_egg = "Humpty" . "Dumpty"; # produces "HumptyDumpty“ "abc" x 3; # produces 'abcabcabc' String and List Operators
  • 20. Number of elements in an array using scalar $count = scalar(@array); Last index in an array using $# $highest = $#array; # $highest = scalar(@array)-1 Append an element to the array $array[scalar(@array)] push @array Insert at the beginning unshift @array Truncating and resizing @array = @array[0..3]; Array Manipulation
  • 21. 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
  • 22. Use <STDIN> to receive 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:"; 14 15 if ( $number1 == $number2 ) { 16 print "$number1 is equal to $number2."; 17 } 18 19 if ( $number1 != $number2 ) { 20 print "$number1 is not equal to $number2."; 21 } 22 23 if ( $number1 < $number2 ) { 24 print "$number1 is less than $number2."; 25 } 26 27 if ( $number1 > $number2 ) { 28 print "$number1 is greater than $number2."; 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 ]"; 10 } 0 Hello 1 283 2 there 3 16.439
  • 25. Data Hierarchy Sally Black Tom Blue File Judy Green Iris Orange Randy Red Record Judy Green Field J u d y Byte (ASCII character J) 01001010 Bit 1
  • 26. Open Seek Truncate Print close File Processing
  • 27.
  • 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" ); 9 open( OUTFILE, ">file.txt" ) 10 or die( "Can't find file.txt : $!" ); 11 print( "Outputting to file" ); 12 print( OUTFILE "There was an old lady" ); 13 close( OUTFILE ) or die( "Can not close file.txt: $!" ); 14 15 print "The file now contains:"; 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( "Append to the end of the file" ); 22 open( OUTFILE, ">>file.txt" ) 23 or die( "Can not open file.txt: $!" ); 24 print( OUTFILE "who lived in a shoe." ); 25 close( OUTFILE ) or die( "Can not close file.txt: $!" ); 26 27 print( "It now reads:" );
  • 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 output Outputting to file The file now contains: There was an old lady   Append to the end of the file It now reads: There was an old lady who 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" ); 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]!" ) ); 28 print( p( i( "You will now be redirected to our home page." ) ) ); 29 }
  • 31. 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
  • 32. perlmyscript -u sventek -p cuckoo Example
  • 33. # number of arguments 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!" ); 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( "" ); 20 print( "It is ", -s $file, " bytes." ); # 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." ); 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." ); 29 }
  • 35. 2 ways for concurrency Process Each task has its own separate memory space Less portable Multithreading Use the same memory process The race condition The timing of threads Synchronization Not possible with processes Each knows when its data area is manipulated Process Management
  • 36. ways to fork Call the systems fork command Not always available Fork Parent process Calls the fork function Child process Created by the fork function Each has a process id or pid Parent returns child pid and undef if unsuccessful Child returns 0 The 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 process 13if ( $pid = fork() ) { 14 sleep( 1 ); 15 print( "Parent executing." ); 16 sleep( 2 ); 17 print( "Parent finished." ); 18 } 19elsif ( defined( $pid ) ) { Executes in the child process 20 sleep( 1 ); 21 print( "Child executing." ); 22 sleep( 2 ); Sleep is used to slow the program down 23 print( "Child finished." ); 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." ); 35 36 sleep( 3 ); 37 sleep( 3 ); 38$end = time(); 39 40 print( "That took " ); 41 print( $end - $middle ); 42 print( " seconds without fork." ); 43 print( "Total of ", ( $end - $start ), " seconds." ); 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 processes 11if ( ( $pid = fork() ) && ( $pid2 = fork() ) ) { 12 print( "I have to wait for my kids." ); 13 my $straggler = wait(); 14 print( "Finally $straggler finished, now I can go." ); 15 } 16elsif ( $pid && defined( $pid2 ) ) { Will not print until all the children are done 17 sleep( 2 ); 18 print( "Kid 2: So is mine..." ); 19 sleep( 4 ); 20 exit(); Child 1 21 } 22elsif ( defined( $pid ) ) { 23 sleep( 1 ); Child 2 24 print( "Kid 1: My parent is patient..." ); 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 processes 11if ( ( $pid = fork() ) && ( $pid2 = fork() ) ) { 12 print( "I have to wait for my kids." ); 13my $straggler = waitpid( $pid, 0 ); 14 print( "Finally $straggler finished, now I can go." ); 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..." ); 19 sleep( 4 ); 20 print( "Kid 2: Hey! Wait for me!!!" ); 21 exit(); 22 } 23 elsif ( defined( $pid ) ) { 24 sleep( 1 ); 25 print( "Kid 1: My parent is patient..." ); 26 sleep( 2 ); 27 } 28 else { 29 die( "Forking problems: " ); 30 }
  • 41. 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!!!
  • 42. The exec function Used to execute other programs from a program Uses system shell to invoke a program Now program replaces current program’s process When new program terminates so does the old one Arguments passed is the program opened All wild cards that work on the system are valid If a list is passed First is the program The rest of the list is arguments to pass to that command without system processing The system and exec functions
  • 43. The system function Same as exec function The only difference is that the process is returned to the program when the opened program terminates This is done using a fork function and making one wait The 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." ); 14 print( "Type clear on a blank line to start over." ); 15 print( "Type quit on a blank line when you are finished." ); 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." ); 24 print( "Type clear on a blank line to start over." ); Opens the file to write to 25 print( "Type quit on a blank line " ); 26 print( "when you are finished." ); 27 open( FILE, ">$file" ) or die( "Cannot open: $!" ); 28 }
  • 45. 29 else { Prints to the file 30 print( FILE ); 31 } Closes the file 32 } 33 34close( FILE ) or die( "Cannot close: $!" ); What file would you like to create? hello.pl Type 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 );
  • 47.
  • 48.
  • 49. The open function Places 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 handle If at the end the output of a file is attached to a file handle Write to the handle to modify the input Read from the handle to modify the output The open2 function Allows the use of both STDIN and STDOUT The open3 function Allows the programmer to obtain the STDERR Controlling 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 STDIN Writes data to MORE 6 use strict; 7 Closes the pipes 8open( 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: $!" );
  • 51.
  • 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 date 11if ( $^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( "", $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 $_, "" ); 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.UtBnc 2 My6jwfxg7zFGE 3 My3G3DtIRpQEA 4 Myza94uYasdEE 5 MyCBteM4CIuTk 6 MyWRtG.HnvdL2 7 Myb8qLeBJ6TlM 8 MyE6k76L3NeoE 9 MyxpYOghD0TIE 10 MyI8Uhkz4HPjY 11 MyB3G7m.CDII6 12 MyugXM4mJTc1c 13 My9OUTHS6M.jg 14 My8UYE/LL8dgU 15 MyYAcz4F1r.to 16 MycPbNadoaNYo 17 MyXdTeyyclDNY 18 MyTm8RxjwtKO. 19 My2Q98KujB0i6 20 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( "" ); 13 } A simple program the displays this line for output after being encrypted
  • 56. The pipe function Used to connect file handles of parent and children programs Allows them to communicate to each other Should set $| to flush after each output Helps to prevent deadlock Using open with filename “-” Returns a handle that is a duplicate of STDIN or STDOUT Communicating 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 versa 9pipe( 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 "$_" ); 20 print( "I said $_, " ); 21 chomp( my $response = <PARENTINPUT> ); 22 print( "and he said $response!" ); 23 } 24 25 close( PARENTOUTPUT ) or Closes the parent input and output handles 26 die( "Cannot close PARENTOUTPUT: $!" ); 27 close( PARENTINPUT ) or 28 die( "Cannot close PARENTINPUT: $!" ); 29 }
  • 58. The child code 30elsif ( defined( $pid ) ) { 31 close( PARENTOUTPUT ) or Closes 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, "" ); 39 } 40 41 close( CHILDOUTPUT ) or Closes 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." ); 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 handle 10if ( my $pid = open( CHILD, "-|" ) ) { 11 my $i; 12 Displays the line number 13while ( <CHILD> ) { 14 print( "Line ", ++$i, ": $_" ); 15 } 16 17 close( CHILD ) or die( "Cannot close: $!" ); 18 } Will output the lines synchronized with the line number output 19elsif ( defined( $pid ) ) { 20 print( "I am doing some" ); 21 print( "processing here" ); 22 print( "that produces" ); 23 print( "multiple lines" ); 24 print( "of output." ); 25 exit(); 26 } 27 else { 28 print( "Could not fork." ); 29 } Line 1: I am doing some Line 2: processing here Line 3: that produces Line 4: multiple lines Line 5: of output.
  • 60. Signals Messages that are delivered to a program by the OS Allow processes to communicate with one another Signals are generated by several things Errors Events User input Internally from a program Most signals can be overridden SIGKILL and SIGSTOP cannot be overridden Used as a last resort for programs that stop responding Signals Handling
  • 61. Special Signals __DIE__ (two underscores (_)) Used to override the die command Not effective when first invoked Prevents infinite recursion __WARN__ Used to override the warn command DEFAULT Returns a signal to its original state IGNORE Ignores a signal Signals Handling (II)
  • 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' } = amp;stop; 12 13while ( $count ) { 14 print( "Hooray!" ); 15 print( "" ); 16 sleep( 1 ); 17 } 18 19 sub stop 20 { 21 $SIG{ 'INT' } = amp;stop; 22 $count--; 23 print( "$count" ); 24 25 unless ( $count ) { 26 print( "Sorry, I did not want to stop..." ); 27 } 28 }
  • 64. Hooray! Hooray! 2 Hooray! Hooray! Hooray! 1 Hooray! 0 Sorry, I did not want to stop...
  • 65. The kill function Used to send signals to another process First argument is the signal to be sent Rest of the arguments are the processes to send the signal to Terminating children Leave behind zombies in process table Allow parent to figure out if the child ended normally Reaping is performed to eliminate zombies Use the wait or waitpid functions to do additional operations The IGNORE statement is used to remove the children from the table Sending 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 } = amp;user1; Calls the desired functions 10 $SIG{ USR2 } = amp;user2; 11 $| = 1; 12 13 sub user1 14 { 15 $SIG{ USR1 } = amp;user1; Displays when the signal is received 16 print( "I have received SIGUSR1." ); 17 } 18 19 sub user2 20 { 21 $SIG{ USR2 } = amp;user2; 22 print( "I have received SIGUSR2." ); 23 } 24
  • 67. 25 if ( my $pid = fork() ) { Sends a signal using the kill function 26 kill( 'USR1', $pid ); 27 kill( 'USR2', $pid ); 28 print( "I have just sent two signals." ); 29 sleep( 2 ); 30 print( "Now I am going to send a few more." ); 31 kill( USR2 => $pid ); 32 kill( USR1 => $pid ); 33 print( "Parent done." ); 34 } 35 elsif ( defined( $pid ) ) { 36 sleep( 5 ); 37 print( "Kid done." ); 38 exit(); 39 } 40 else { 41 print( "Forking error..." ); 42 } 43 44 wait(); fig18_15.pl Program Output I 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. Mounting and Unmounting File Systems Configure interface. Soft/Hard Linking. FreeBSD Administration
  • 69. Adding Packages pkg_add -r lsof-4.56.4 Deleting Packages pkg_delete xchat-1.7.1 Packages
  • 70. Makefile: The Makefile contains various statements that specify how the application should be compiled and where it should be installed on your system distinfo 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.
  • 72. 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] ... #
  • 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 File The /etc/fstab file contains a list of lines of the following format: device /mount-point fstype options dumpfreqpassn mount-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 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
  • 77.
  • 78. Setup values as follows:hostname="fbsdx.test.com"ifconfig_lnc0="inet 192.168.0.6 netmask 255.255.255.0"
  • 79. Ethernet interface name can be Obtained using ifconfig -a command.
  • 80. You should run /etc/netstartscript or /etc/rc.d/netif restart.Interface Configuration
  • 81. 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
  • 82.
  • 83. If the original program, 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 a soft link called myfilelink.txt that points to a file called myfile.txt, use this: ln-s myfile.txt myfilelink.txt Soft links
  • 86.
  • 87. If the original program or file is renamed, moved, or deleted, the hard link is NOT broken
  • 88. Hard links cannot span 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 files from different file systems.
  • 90. To create a hard link called myhardlink.txt that points to a file called myfile.txt, use this: ln myfile.txt myhardlink.txtHard links