Perl Network Programming notes (-)

Source: Internet
Author: User
Tags perl script


When the perl script starts executing, 3 file handles are opened by default: STDOUT, STDIN, STDERR

STDOUT (standard outpu) is the default output file handle. Send to this file handle
The data is displayed on a user-specified output device, usually a command window where the script runs.

STDIN (standard input) is the default input file handle. The data read from this handle is taken from
The user selects an input device, usually a keyboard.

STDERR (ie, standard error) is used for error messages, diagnostics, tuning, and other similar incidental output.

$ line = <>; #Read one line at a time
@line = <>; #Read all data


$ bytes = read (FILEHANDLE, $ buffer, $ lenght, [, $ offset])
$ bytes = sysread (FILEHANDLE, $ buffer, $ length, [, $ offset])


The read () function and sysread () function read arbitrary data from the specified file handle.
The length read can be up to $ length bytes, and the data read is placed in $ buffer.
Both functions return the number of bytes actually read, or a number if the end of the file.

The main difference between read () and sysread () is that read () uses standard I / O buffering while sysread () does not.
This means that read () does not return until the actual number of bytes required or the end of the file is read.
Instead, the sysread () function returns part of the data, it is guaranteed to return at least 1 byte, but if it cannot
Read the required number of bytes immediately from the file handle, and it will return what it can read.



$ bytes = syswrite (FILEHANDLE, $ data [, $ lenght [, $ offset]])
The syswrite () function is a choice for writing a file handle, which gives more control over the writing process.
Its parameters are a file handle and a scalar value (variable or string literal). It writes data to a file handle and returns success
The number of bytes written. By default, syswrite () attempts to write the entire contents of $ data, starting with the first character of the string. You can pass
Provide optional $ length and $ offset to change the above behavior of syswrite (), in which case syswrite ()
$ Length will be written from the position specified by $ offset.


$ previou = select (FILEHANDLE);
The select () function is used to change the default output file handle of print (). It sets the file handle name to the default value and returns the previous default
The name.select () function is a version with four parameters for multiplexing.


$! Error returned by context

eof () function, used to display the EOF condition of the test bar handle


End of line
  On unix systems, the line ends with a character (LF, octal \ 012 in ASCII table);
  On Macintosh systems, the line ends with a carriage return character (CR, octal \ 015);
  On Windows / DOS systems, it is determined that the line feed ends with two characters, one is a carriage return / line feed pair (CRLF, or octal \ 015, \ 012)
  Most line-oriented web servers also use CRLF line breaks.

  Perl provides a way to check and change the end-of-line character. The global variable $ / contains the current character or sequence of characters used to refer to the end of the line.
  By default, this variable is set to \ 012 on UNIX systems, \ 015 on Macintosh systems, and on Windows AND DOS systems.
  Set to \ 015 \ 012.

  And the line-oriented <> input function will read data from the specified handle until it encounters the end-of-line character contained in $ / and then it returns
  The file with the end-of-line character sequence attached to this line. The chomp () function finds the end-of-line character at the end of the file string based on the current value of $ /
  Sequence and delete it.

  binmode () function turns off character conversion
  binmode (FILEHANDLE, [, $ disciplie])
  The binmode () function turns on binary mode for the file handle and cancels character conversion. This function should
  The file handle is called before doing any I / O operations.


  open (FILEHANDLE, $ mode, $ path);

  Mode Description
  <Open file for reading
  > Intercept file length is 0 and open for writing
  >> Open file for adding without truncation
  +> Truncate the file and then open it for reading / writing
  <+ Open file for read / write without truncation


sysopen (FILEHANDLE, $ filename, $ mode [, $ perms]);
The sysopen () function opens the file specified by $ filename, using the I / O mode specified by $ mode. If the file does not exist,
And $ mode specifies that the file should be created. The value of the optional $ perms indicates the permission bit of the newly created file.

Constant Description
O_RDONLY open for read-only
O_WRONLY open for write only
O_RDWR open for read / write
When O_EXCL and O_CREATE are used in combination, the file is created when the file does not exist and fails when the file exists
O_TRUNC truncates the file to length 0 if it already exists
O_APPEND Open file in add mode (equivalent to ">>" of open ())
O_NOCITY If the file is a terminal device, open it and do not allow it to become the controlling terminal of the process
O_NONBLOCK Open file in non-blocking mode
O_SYSNC opens the file synchronously, blocking all write operations until the physical write of the data is completed



Buffering and blocking
  When print () and syswrite () are called on a file handle, the actual output operation does not happen immediately. If you write to a file,
  The system must wait for the writing head to reach the appropriate position on the disk drive, and wait for the rotating disk to bring the corresponding position of writing under the writing head.

The buffer is conceptually a circular FIFO (First In First Out) data structure. When the data written exceeds the end of the buffer memory area, the operating system simply
Write new data at the beginning of the buffer. The operating system maintains two pointers in each I / O buffer. The write pointer points to the buffer where new data enters
District place. The data at the position pointed by the read pointer is removed from the buffer and written to the next destination.



Two methods can solve the stdio buffering problem. One method is to enable "autoflush" mode for the file handle. "autoflush" mode
Used only for output operations. When autoflush mode is activated, each time print () is called perl will tell stdio to copy the
Send the contents of the buffer.
To enable autoflush mode, set the special variable $ | to the value true. autoflush mode affects the currently selected file handle,
So select the previously selected file handle for a particular file handle (using select ()).

my $ previous = select (FH);
$ | = 1;
select ($ previous);

select ((select (FH), $ | = 1) [0])

Another way to avoid stdio buffering problems is to use sysread () and syswrite () calls. These two calls are bypassed
The stdio library goes directly to the operating system I / O calls. An important point of these two calls is that they can be used with other low-level I / O calls.
(Such as the parameter select () call) is very interoperable, and it can interoperate well with advanced techniques (such as non-blocking I / O).




Passing and storing file handles

Sometimes you need to check a scalar to see if it contains a valid file handle.The fileno () function can meet this need;

$ integer = fileno (FILEHANDLE);

The fileno () function accepts a file handle as a string, typeglob, or typeglob reference. If the file handle is valid,
Then fileno () returns the file descriptor of the file handle. The file descriptor is a small integer that uniquely identifies the operation
The file handle of the system. Generally, STDIN, STDOUT, and STDERR are descriptors 0, 1, and 2 (if you close and reopen them, you
To change its descriptor). Other file handles have descriptors greater than 3.



Error detection

use Errno qw (EACCES ENOENT);

my $ resutl = open (FH, "/ etc / passwd1");
if (! $ resutl) # oops, something went wrong
{
 if ($! == EACCES)
 {
    warn "You do not have permission to open the file. \ n";
 }
 elsif ($! == ENOENT)
 {
    warn "File or directory not found. \ n";
 }
 else
 {
    warn "Some other error occurred: $! \ n";
 }
}


IO :: Handle module and IO :: File module

#! / usr / bin / perl
#Open a file and count the number of lines in the file
use strict;
use warnings;
use IO :: File;

my $ file = shift;
my $ counter = 0;
my $ fh = IO :: File-> new ($ file) or die "Cant open $ file: $! \ n";
while (defined (my $ file = $ fh-> getline ()))
{
   $ counter ++;
}

STDOUT-> print ("Counted $ counter lines \ n");


IO :: File-> new ($ filename [, $ mode [, $ perms]])
The new () method is the main constructor of IO :: File. It is a unified replacement for open () and sysopen ().
For example: open the specified file for adding:
$ fh = IO :: File-> new ("> darkstar, txt");

$ fh = IO :: File-> new_tmpfile ();
The new_tmpfile () constructor is called with no arguments, it creates a temporary file and opens it for reading and writing.
On UNIX systems, the file is anonymous, meaning it is not visible to the file system. When revoking an IO :: File object, this
File and its entire contents will be deleted automatically. This construct is useful for storing large numbers of temporary files.
$ resutl = $ fh-> close;

$ result = $ fh-> open ($ file [, $ mode [, $ perms]]);
You can use the open () method to reopen a file handle object for the specified person. The input parameters are the same as new (). method
The result indicates whether the open operation completed successfully.
This method is mainly used to reopen the standard file handles STDOUT, STDIN, STDERR.
STDOUT-> open ("> log.txt") or die "Cant reopen STDOUT: $!";
The call to print () will now write to the file log.txt

$ result = $ fh-> print (@args);
$ result = $ fh-> printf ($ fmt, @ args);


$ bytes = $ fh-> write ($ data [, $ length [, $ offset]]);
$ bytes = $ fh-> syswrite ($ data [, $ length [, $ offset]]);

The print (), printf () and syswrite () methods work exactly the same as their built-in counterparts.
For example, print () receives a series of data items, writes them to a file handle object, and returns true when successfully written.

write () and read () Instead, write a byte stream to a file handle object and return the number of bytes successfully written.


$ lines = $ fh-> getline;
@ linges = $ fh-> getlines;
$ bytes = $ fh-> read ($ buffer, $ legal [, $ offset])
$ bytes = $ fh-> sysread ($ buffer, $ length [, $ offset])
The getline () and getlines () methods replace the <> operator together. getline () reads a line from a file handle object
And return it, the behavior of the context and list context is the same. The behavior of the getlines () method in a list context and <>
Similarly, return a list of all available rows. getline) will return undef at the end of the file;

$ prev
ious = $ fh-> autoflush ([$ boolean])
The autoflush () method gets or sets the autoflush mode of the file handle object. When called with no arguments, it turns on autoflush.
When called with a single boolean parameter, it sets autoflush to the specified state. In both cases, autoflush () returns autoflush
The previous value of the state.
$ boolean = $ fh-> opened;
The open () method returns true if the file handle object is valid. It costs:
defined filno ($ fh);
$ boolean = $ fh-> eof;

This method returns true if the next read operation on the file handle object will return EOF;

 $ fh-> flush;
 The flush () method immediately "gush" any data buffered in the file handle object. If the file handle is used for writing, buffer it
 Data is written to disk (or pipe, network). If the file handle is used for reading, any data in the buffer is discarded.
 Read from disk once.

 $ boolean = $ fh-> block ([$ boolean])
 The blocking () method opens and closes blocking mode as a file handle.

$ fh-> clearerr;
$ boolean = $ fh-> error;
If you want to perform a series of I / O operations and only check the status of errors after completion, then these two methods will be convenient.
Error () if any error occurred since the file handle was created or since the last call to clearerr ()
A true.clearerr () method will be returned to clear the error flag.



-------------------------------------------------- ---
Processes, pipes and signals
-------------------------------------------------- ---


process

Perl supports two types of multitasking. One type is based on the traditional UNIX multi-process model, allowing the current process to pass fork ()
The function copies itself. One process does one task, and the other process does another task.
The other is based on modern, more lightweight "threads". Keep all tasks in a single process. However, a single program can have
Multiple execution threads run in it, and each thread runs independently of the other threads.

Perl's fork () function takes no parameters and returns a numeric result code. When fork () is called, it generates a
Exact copy. This copy, called a child process, shares all variables, file handles (including data in standard I / O buffers), and other
All current values of the data knot. In fact, this copying process even has memory that calls fork ().

After fork () is called, both the parent and child processes check the return value of the function. In the parent process, fork () returns the PID of the child process.
In the child process, fork () returns the value 0. If the code finds that it is the parent process, it will start to do something, if it is a child process
Will do another thing.

$ pid = fork ();
Forked a new process. Returns the PID of the child process in the parent process and 0 in the child process. When an error occurs (such as not enough
Memory-derived child process), return undef, and set $! To the appropriate error message.

If the parent and child processes want to communicate with each other after calling fork (), they can be done through a pipeline or through shared memory
To be done. For simple messages, the parent and child processes can use the kill () function to signal each other's PID. Parent process
The PID of the child process is obtained from the result code of fork (), and the child process obtains the PID of the parent process by calling getppid ().
A process can obtain its own PID by checking the $$ special variable.

$ pid = getppid ();
Returns the PID of the parent process. Every perl script has a parent process, even those perl scripts run directly from the command have a parent process.
(Their parent process is the shell process)

$$
The $$ variable holds the PID of the current process. It is readable but cannot be changed.


If the child process wishes, it can also call fork () to create the grandchild process. The original process parent process can also call fork () again
You can create child processes, as well as child and grandchild processes. In this way, perl scripts can create an entire tribe of processes.
Each member of this tribe belongs to the same process group

Each process has a unique ID, which is usually the same as the process ID of the shared ancestor. This value can be obtained by calling getpgrp ():
$ processid = getpgrp ([$ pid]);
For the process specified by $ pid, the getpgrp () function returns its process group ID. If no PID is specified, it returns the process group of the current process.
#! / usr / bin / perl
use strict;
use warnings;

print "PID = $$ \ n";

my $ child = fork ();
die "Cant fork: $! \ n" unless defined $ child;

if ($ child> 0)
{
   print "Parent process: PID = $$, child = $ child \ n";
}
else
{
   #child process
   my $ ppid = getppid ();
   print "Child process: PID = $$, Parent = $ ppid \ n";
}
~


system () and exec ()
Perl's other method of running a child process uses system (). system () to run another program as a child process and wait for it to complete,
Then return. If the operation is successful, system () returns a result code of 0, otherwise, if the program cannot start running, it returns -1, if the program
Error termination returns the termination status of the program.

$ status = system (‘command and aguments’);
$ status = system (‘command‘, ’and’, ‘arguments’);
The system () function executes a command as a child process and waits for it to terminate. The command and its parameters can be specified as a single string,
Or specify it as a list that contains the command and its parameters, but all as separate elements. 


Perl Network Programming notes (-)


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.