This document provides an overview of the Perl programming language. It discusses scalars, arrays, hashes, references, subroutines, packages, warnings, strictness, password encryption, file handling, command line arguments, and process management in Perl. Specific topics covered include using @ and $ prefixes for arrays and scalars, accessing elements of arrays and hashes, defining and calling subroutines, using crypt() for password hashing, opening/writing/reading files, and using fork() to create child processes. Examples of code are provided to demonstrate many of these Perl concepts.
전체목차: https://netpple.github.io/docs/make-container-without-docker/
클라우드 위에서 컨테이너에 가상 IP를 부여하고 이러한 가상 IP대역을 기반으로 컨테이너 간에 통신이 어떻게 가능한 것일까요?
동적으로 오버레이 네트워크를 구성해 봅니다.
지난 시간 가상IP 대역을 기반으로 서로 다른 물리노드 간의 통신을 가능하기 위하여 가상 디바이스를 생성하고 ARP cache와 Bridge FDB 정보를 입력해주고, vxlan 기반의 UDP encapsulation과 터널링을 통하여 가상디바이스의 L2정보를 목적지 노드로 전송하여 통신이 되는 것을 확인하였습니다.
이에 대한 내용을 바탕으로 가상네트워크를 추가하고 통신할 때 커널 이벤트(NETLINK)를 캐치하여 동적으로 arp, fdb 갱신처리하여 컨테이너 간에 통신이 가능하도록 구성해 봅니다.
Make container without_docker_6-overlay-network_1 Sam Kim
분산환경에서 컨테이너 간의 통신은 어떻게 이루어 지는 것일까요? 3,4편에서는 호스트 안에 가상네트워크를 만들어보았습니다. 6편에서는 이를 바탕으로 분산환경에서 호스트 간에 가상 네트워크로 통신이 가능하도록 만들어 봅니다. 이 방법은 실제 쿠버네티스 flannel 등의 CNI에서 사용하고 있는 vxlan 기반의 오버레이 네트워크 구성을 다룹니다.
전체목차: https://netpple.github.io/docs/make-container-without-docker/
클라우드 위에서 컨테이너에 가상 IP를 부여하고 이러한 가상 IP대역을 기반으로 컨테이너 간에 통신이 어떻게 가능한 것일까요?
동적으로 오버레이 네트워크를 구성해 봅니다.
지난 시간 가상IP 대역을 기반으로 서로 다른 물리노드 간의 통신을 가능하기 위하여 가상 디바이스를 생성하고 ARP cache와 Bridge FDB 정보를 입력해주고, vxlan 기반의 UDP encapsulation과 터널링을 통하여 가상디바이스의 L2정보를 목적지 노드로 전송하여 통신이 되는 것을 확인하였습니다.
이에 대한 내용을 바탕으로 가상네트워크를 추가하고 통신할 때 커널 이벤트(NETLINK)를 캐치하여 동적으로 arp, fdb 갱신처리하여 컨테이너 간에 통신이 가능하도록 구성해 봅니다.
Make container without_docker_6-overlay-network_1 Sam Kim
분산환경에서 컨테이너 간의 통신은 어떻게 이루어 지는 것일까요? 3,4편에서는 호스트 안에 가상네트워크를 만들어보았습니다. 6편에서는 이를 바탕으로 분산환경에서 호스트 간에 가상 네트워크로 통신이 가능하도록 만들어 봅니다. 이 방법은 실제 쿠버네티스 flannel 등의 CNI에서 사용하고 있는 vxlan 기반의 오버레이 네트워크 구성을 다룹니다.
1,2편에서 다룬 chroot와 pivot_root를 통해서 root filesystem을 isolation하였습니다. 마운트 네임스페이스는 파일시스템 마운트를 isolation 하는 것으로 이미 pivot_root에서도 사용하였지만, mount 처리를 격리함으로써 컨테이너 내부의 파일시스템 구조를 독립적으로 유지합니다. 실제 도커 컨테이너의 이미지 tarball을 이용하여 pivot_root와 mount namespace까지 적용하여 실제 도커 방식과 유사하게 컨테이너를 기동하여 봅니다. 그리고, 컨테이너 이미지 용량/중복을 해결하기 위한 overlayFS 에 대하여 다룹니다.
https://netpple.github.io
Agenda:
In this session, Shmulik Ladkani discusses the kernel's net_device abstraction, its interfaces, and how net-devices interact with the network stack. The talk covers many of the software network devices that exist in the Linux kernel, the functionalities they provide and some interesting use cases.
Speaker:
Shmulik Ladkani is a Tech Lead at Ravello Systems.
Shmulik started his career at Jungo (acquired by NDS/Cisco) implementing residential gateway software, focusing on embedded Linux, Linux kernel, networking and hardware/software integration.
51966 coffees and billions of forwarded packets later, with millions of homes running his software, Shmulik left his position as Jungo’s lead architect and joined Ravello Systems (acquired by Oracle) as tech lead, developing a virtual data center as a cloud service. He's now focused around virtualization systems, network virtualization and SDN.
In this talk, Gil Yankovitch discusses the PaX patch for the Linux kernel, focusing on memory manager changes and security mechanisms for memory allocations, reads, writes from user/kernel space and ASLR.
Logical Volume Management ("LVM") on linux looks like a complicated mess at first. The basics are not all that hard, and some features like mirroring, dynamic space management, snapshots for stable backups, mirroring, and over-provisioning via thin volumes can save a lot of time and effort.
Building Network Functions with eBPF & BCCKernel TLV
eBPF (Extended Berkeley Packet Filter) is an in-kernel virtual machine that allows running user-supplied sandboxed programs inside of the kernel. It is especially well-suited to network programs and it's possible to write programs that filter traffic, classify traffic and perform high-performance custom packet processing.
BCC (BPF Compiler Collection) is a toolkit for creating efficient kernel tracing and manipulation programs. It makes use of eBPF.
BCC provides an end-to-end workflow for developing eBPF programs and supplies Python bindings, making eBPF programs much easier to write.
Together, eBPF and BCC allow you to develop and deploy network functions safely and easily, focusing on your application logic (instead of kernel datapath integration).
In this session, we will introduce eBPF and BCC, explain how to implement a network function using BCC, discuss some real-life use-cases and show a live demonstration of the technology.
About the speaker
Shmulik Ladkani, Chief Technology Officer at Meta Networks,
Long time network veteran and kernel geek.
Shmulik started his career at Jungo (acquired by NDS/Cisco) implementing residential gateway software, focusing on embedded Linux, Linux kernel, networking and hardware/software integration.
Some billions of forwarded packets later, Shmulik left his position as Jungo's lead architect and joined Ravello Systems (acquired by Oracle) as tech lead, developing a virtual data center as a cloud-based service, focusing around virtualization systems, network virtualization and SDN.
Recently he co-founded Meta Networks where he's been busy architecting secure, multi-tenant, large-scale network infrastructure as a cloud-based service.
The latest releases of today’s popular Linux distributions include all the tools needed to do interesting things with Linux containers.
For the Makefile MicroVPS project, I set out to build a minimal virtual private server-like environment in a Linux container from scratch.
These are my requirements for the MicroVPS:
Minimal init sequence
Most of what happens in a rc.sysinit file is not needed (or wanted) in a container. However, to work like a virtual private server, the MicroVPS will need some kind of init system. The absolute minimum would be enough to start the network and at least one service.
Native network namespace
The MicroVPS will have a dedicated network namespace. It should be easy to configure.
Native package management
The package set installed in the container image will be managed using native tools like deb or rpm.
Automated build
An automated repeatable build process is a must.
Fast iteration cycle
The building and testing cycle must be fast enough not to drive me insane.
Easy management
It should be easy to distribute, monitor, and run a MicroVPS container.
In this tutorial, I will show how to use the tools included with Linux to build a virtual private server in a Linux container from scratch, using GNU Make to automate the build process.
Dima Krasner talks about FUSE, Filesystem in Userspace, its pros and cons, usage, tips and tricks, and more.
Dima is a senior developer at Sam Seamless Network.
When your whole system is unresponsive, how to investigate on this failure ?
We'll see how to get a memory dump for offline analysis with kdump system.
Then how to analyze it with crash utility.
And finally, how to use crash on a running system to modify the kernel memory (at your own risks !)
Useful Linux and Unix commands handbookWave Digitech
This article provides practical examples for most frequently used commands in Linux / UNIX. Helpful for Engineers and trainee engineers, Software developers. A handy notes for all Linux & Unix commands.
1,2편에서 다룬 chroot와 pivot_root를 통해서 root filesystem을 isolation하였습니다. 마운트 네임스페이스는 파일시스템 마운트를 isolation 하는 것으로 이미 pivot_root에서도 사용하였지만, mount 처리를 격리함으로써 컨테이너 내부의 파일시스템 구조를 독립적으로 유지합니다. 실제 도커 컨테이너의 이미지 tarball을 이용하여 pivot_root와 mount namespace까지 적용하여 실제 도커 방식과 유사하게 컨테이너를 기동하여 봅니다. 그리고, 컨테이너 이미지 용량/중복을 해결하기 위한 overlayFS 에 대하여 다룹니다.
https://netpple.github.io
Agenda:
In this session, Shmulik Ladkani discusses the kernel's net_device abstraction, its interfaces, and how net-devices interact with the network stack. The talk covers many of the software network devices that exist in the Linux kernel, the functionalities they provide and some interesting use cases.
Speaker:
Shmulik Ladkani is a Tech Lead at Ravello Systems.
Shmulik started his career at Jungo (acquired by NDS/Cisco) implementing residential gateway software, focusing on embedded Linux, Linux kernel, networking and hardware/software integration.
51966 coffees and billions of forwarded packets later, with millions of homes running his software, Shmulik left his position as Jungo’s lead architect and joined Ravello Systems (acquired by Oracle) as tech lead, developing a virtual data center as a cloud service. He's now focused around virtualization systems, network virtualization and SDN.
In this talk, Gil Yankovitch discusses the PaX patch for the Linux kernel, focusing on memory manager changes and security mechanisms for memory allocations, reads, writes from user/kernel space and ASLR.
Logical Volume Management ("LVM") on linux looks like a complicated mess at first. The basics are not all that hard, and some features like mirroring, dynamic space management, snapshots for stable backups, mirroring, and over-provisioning via thin volumes can save a lot of time and effort.
Building Network Functions with eBPF & BCCKernel TLV
eBPF (Extended Berkeley Packet Filter) is an in-kernel virtual machine that allows running user-supplied sandboxed programs inside of the kernel. It is especially well-suited to network programs and it's possible to write programs that filter traffic, classify traffic and perform high-performance custom packet processing.
BCC (BPF Compiler Collection) is a toolkit for creating efficient kernel tracing and manipulation programs. It makes use of eBPF.
BCC provides an end-to-end workflow for developing eBPF programs and supplies Python bindings, making eBPF programs much easier to write.
Together, eBPF and BCC allow you to develop and deploy network functions safely and easily, focusing on your application logic (instead of kernel datapath integration).
In this session, we will introduce eBPF and BCC, explain how to implement a network function using BCC, discuss some real-life use-cases and show a live demonstration of the technology.
About the speaker
Shmulik Ladkani, Chief Technology Officer at Meta Networks,
Long time network veteran and kernel geek.
Shmulik started his career at Jungo (acquired by NDS/Cisco) implementing residential gateway software, focusing on embedded Linux, Linux kernel, networking and hardware/software integration.
Some billions of forwarded packets later, Shmulik left his position as Jungo's lead architect and joined Ravello Systems (acquired by Oracle) as tech lead, developing a virtual data center as a cloud-based service, focusing around virtualization systems, network virtualization and SDN.
Recently he co-founded Meta Networks where he's been busy architecting secure, multi-tenant, large-scale network infrastructure as a cloud-based service.
The latest releases of today’s popular Linux distributions include all the tools needed to do interesting things with Linux containers.
For the Makefile MicroVPS project, I set out to build a minimal virtual private server-like environment in a Linux container from scratch.
These are my requirements for the MicroVPS:
Minimal init sequence
Most of what happens in a rc.sysinit file is not needed (or wanted) in a container. However, to work like a virtual private server, the MicroVPS will need some kind of init system. The absolute minimum would be enough to start the network and at least one service.
Native network namespace
The MicroVPS will have a dedicated network namespace. It should be easy to configure.
Native package management
The package set installed in the container image will be managed using native tools like deb or rpm.
Automated build
An automated repeatable build process is a must.
Fast iteration cycle
The building and testing cycle must be fast enough not to drive me insane.
Easy management
It should be easy to distribute, monitor, and run a MicroVPS container.
In this tutorial, I will show how to use the tools included with Linux to build a virtual private server in a Linux container from scratch, using GNU Make to automate the build process.
Dima Krasner talks about FUSE, Filesystem in Userspace, its pros and cons, usage, tips and tricks, and more.
Dima is a senior developer at Sam Seamless Network.
When your whole system is unresponsive, how to investigate on this failure ?
We'll see how to get a memory dump for offline analysis with kdump system.
Then how to analyze it with crash utility.
And finally, how to use crash on a running system to modify the kernel memory (at your own risks !)
Useful Linux and Unix commands handbookWave Digitech
This article provides practical examples for most frequently used commands in Linux / UNIX. Helpful for Engineers and trainee engineers, Software developers. A handy notes for all Linux & Unix commands.
Wikipedia: A Tool for Teaching (Skeptical) Research Elizabeth Nesius
Wikipedia is one form of social media, and often at the bull’s eye of “new media myopia” (Obar, 2012). When asked to do research, Wikipedia is usually the first place students look. While we might want to teach students that Wikipedia is one place to start, it usually is not the one place where we want them to end. Therefore, incorporating Wikipedia into classroom instruction is a powerful way to teach students how to analyze the sources they use. This presentation will introduce educators to possible ways Wikipedia can be utilized in the classroom as a teaching and learning tool.
Book IV helps you to find ways of describing your research experience and interests that demonstrate your commitment to empirically-based treatment approaches, even if you are primarily training to become a clinical psychologist.
Artificial Intelligence Programming in Art by Mohamed FaragMohammed Farrag
This presentation is an ignite talk for CREATE 2015 event. The talk focused on the revolution from Artificial Intelligence Markup Language (AIML) to Virtual Human Markup Language (VHML)
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
Introduction to AI for Nonprofits with Tapp NetworkTechSoup
Dive into the world of AI! Experts Jon Hill and Tareq Monaur will guide you through AI's role in enhancing nonprofit websites and basic marketing strategies, making it easy to understand and apply.
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
This presentation provides a briefing on how to upload submissions and documents in Google Classroom. It was prepared as part of an orientation for new Sainik School in-service teacher trainees. As a training officer, my goal is to ensure that you are comfortable and proficient with this essential tool for managing assignments and fostering student engagement.
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
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
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
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: $!" );
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
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"
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