开发工具:
文件大小: 504kb
下载次数: 0
上传时间: 2019-08-18
详细说明:In Depth
In this chapter, I’m going to take a look at the support Perl offers for interprocess
communication (IPC). As far as an operating system is concerned, a process is a
running job that has its own execution resources, including share of CPU time.
Your process can start or interact with other In Depth
Youll also find more IPC material in one other place in this book, Chapter 20, on
the Internet and socket programming. Most people think of sockets as an Internet
phenomenon that you use to connect to other machines across the Internet, but
in fact, you can use sockets to connect processes on the same machine.
And. that's it it's time to turn to the immediate solutions now
1934eC1P5
8/3001.3:14PM
cHapter 1 Built-In Functions: Interprocess Communication
i Immediate Solutions
Catching Signals
The Novice Programmer is complaining. "Users are shutting down my script us
ing Ctrl+C, the NP says, which doesnt give me any chance to do any cleanup
catching the INT signal. "Oh? "the NP asks. Tell me more/ "y, you could try
and close my databasc file as it should be closed. "well
n Unix, processes can communicate with each other using signals, and Perl uses
an easy mechanism for catching signals sent to your process: You connect a sig
nal handling subroutine to the signals entry in the predefined %SIG hash. (See
the topic %SIG Signal Handlers"in Chapter 10 for more information.
In this first example, I catch the INT signal, which is sent when the user presses
Ctrl+C. To catch that signal, you connect a signal handler, which I'll call
sig_handler, to the INT signal this way
sSIGiINT-\&sig. handler;
Note that I'n storing a hard reference to sig_ handler in the %sIg hash here. You
can also store symbolic references if you like, but i prefer hard references be
cause they dont cause any confusion if you use this code in a module
The sig_ handler signal handler is just a subroutine. That subroutine gets the
name of the signal passed to it as an argument, so you can display the name of the
signal and quit, like this
sub sig handler f
die" i got signal signal";
Now, you can add code for the rest of the program, and when the user presses
Ctrl+C, the code in sig_ handler will be called (note that you can see the c in
the output)
sub sig handler
e4
1934eC1P5
8/3001,3:14PM
Immediate Solutions
my $signal= shift
die i got signal signe
SSIGlInt -l&sig handle
While(>)t
print
nCI got signal INT at interruptme. p! iine 3
Using a signal handler like this gives you the chance to perform a little cleanup
when the user presses Ctrl+C or you've sent yourself an alarm signal to handle a
timeout(see the topic alarm Send an Alarm Signal"in Chapter 12 ). But, you
should know one thing: Most Unix system library functions (unlike Windows func
tions and even Perl at the deepest level are not re-entrant. When afunction is re
entrant, you can interrupt processing while inside the function and call it again
without any trouble because the original state of the data in the function is stored
on the stack and is restored when the second call to the function exits
If a function is not re-entrant, and you interrupt it and call it again, the original
data will be overwritten when the second call exits the original call to the fund
tion is left in a shambles(and the return address of the original caller is usually
lost as wel, with the result that the process will probably hang
TIP: / once had the pleasure of having to write a Windows program entirely in assembly language, which also meant
making use of assembly language to make it re-entrant so that it could handle multiple concurrent calls. /aon't
recommend doing so unless you have as much patience as time-and a ot of both
You therefore should keep the code in your signal handlers as short as possible
The temptation might be great to add a lot of code after the user has pressed
Ctrl+C, for example, but in fact, you have to keep it minimal
Note that you can make signal handlers anonymous subroutines, like this
SSIGINT- sub
my Signal shift
die "i got signal signal
hile(>)i
print:
Cl got signa: IN at interruptme. p! line 3.
1934eC1P5
8/3001,3:14PM
cHapter 1 Built-In Functions: Interprocess Communication
You can also assign strings such as 'ignore and deFault'to signal handlers
See the topic %SIG Signal Ilandlers'"in Chapter 10 for more information. You
also should note that some signals cant be trapped (orignored), such as the KILL
and stoP signals
Finally, note that you can make a signal handler temporary, either by reassigning
a new value to it (such as 'DEFAULT or by using local like this:
sub do_not_interrupt_me
local sSIgIINTI ignORE
store( gdata)
When the code in the subroutine goes out of scope, the int signal handler is
restored to the value it had before the subroutine was called. (Because Im using
local and not, my here, the samc signal handler will be active for any subroutines
that are called from the current subroutine. See the topic "Whats the Difference
between my and local? "in Chapter 7.)
See also the topic Sending a signal to another Process"in this chapter and the
topic"What Signals Are Available? coming up next
What Signals Are Available?
Okay, the Novice programmer says, I understand that i can catch signals sent
to my process in Unix by using the %SIG hash, but what signals are available? i
need to know that infornation before i can write any signal handlers " That
you say," varies bv system.”“ I knew you' d say that,” the np says.
To see what signals are supported on a particular Unix system, you can use the
kill-l command at the command prompt
%ki11-1
HUP NT IT I TRAP ABR FMT FDF KILL BUS SEGV SYS PPF ARM TERM URG
STOP TSTO CONT CHID TTIN TOU 9 XCPU XFS TAI RM PROF WINCH CST USRI USR2
In Perl code, you can use the Config module and take a look at S Config(sig_name)
like this
use Config
print SConfig[sig_name]":
66
1934eC1P5
8/3001,3:14PM
Immediate Solutions
HUP INT QUIT ILL TRAP ABRT EMT FPE
BUS SEGV SYS PIPE ALRM TERM URG
STOP TSTP CONT CHLD TTIN TTCU I0 XCPU XFSZ VTALRM PROF WINCH LOST USRI SR2
This is all very well, but those names are pretty terse. What do they stand for? You'll
find a list of the standard Unix signals in Table el.l, along with what they do
See also the topics "Catching Signals"and"Sending a Signal to Another process
ater in this chapter.
TE
Table e11 Standard unix signals
Signal
Signal Number
Means
HUP
Hangup
nterrupt
QUIT
Quit
legal instruction
TRAP
Trace trap
ABRT
6
Abort
EMT
Emulator trar
FPE
Athme c exception
KILL
Kill(cannot be caught, blocked, or ignored)
BUS
10
Bus error
SEGV
mentation volati
SYS
Bac argument to system cal
PIPE
ac wr te to pipe or socke
ALRM
14
Aarm clock
TERM
Sottware termination signal
URG
Urgent condition present on socket
STOP
Stop(cannot be caught, blocked, or ignored
TSTP
Stop s gna generated from keyboard
CONT
Continue after sto
CHLD
20
Child status has changed
ITIN
Background read trom control termnal
TTOU
Background write to control terminal
/0 is possible on a descr pto
XCPU
24
CPU time limit exceeded
XFSZ
File size limit exceeded
(continued)
1934eC1P5
7
8/3001.3:14PM
cHapter 1 Built-In Functions: Interprocess Communication
Table e11 Standard Unix signals(continued)
signal
Signal Number
Means
VTALRM
26
Virual time alarm
PROF
Prof ling timer alarm
WINCH
Window change
LOST
Resource lost
USRT
User-defined signal
USR2
31
User-defined sig nal 2
Using Backticks to Pass Commands to the System
I have good news and bad news, the Novice Programmer says. What's the good
news? you ask. Users love iny database program so much they never want to
leave it, the NP says. And, the bad news? you ask. Theyre demanding a way to
execute system commands from inside my program so that they can do thin
like check directories to find files, the nP says. Thats no problem, you say.
' Usc the backticks opcrator to cxccutc a command from insidc your codc
You can use the backticks operator--that is, the backward-leaning single quote
Cto cause Perl to pass a command to the underlying operating systen
For example, in code, you can execute the Cnix uptime command (which shows
how long the computer has been up)this way:
Uptime
uptime
rint uptime
4: 29oil up 18 adys, 21: 22, 13 users, odd average: 0.30, 0.39,0.42
The backticks operator works the same way in MS-DOS. No uptime command is
available in ms-dos, but i can execute a command such as dir this way
sdirlist = dir
print sdirlist
Directory cr C: \per!book\temp
10-07-994:02p
10-07-994:02p
IEMP
3,53510-0/-
eB
1934eC1P5
8/3001.3:15PM
Immediate Solutions
Note that i assigned the return value of the backticks operator, which is the out-
put of the command, to a scalar. You should assign the value in normal circum-
stances because backticks are designed expressly to let you capture a programs
output. (If you just want to run a program, see the topic system Fork and run
Another Program"later in this chapter. Using backticks without assigning a re
turn value to anything is called using backticks in void conteat, and a lot of styl
ists frown on that, approach
TE
In addition, you should check the error returned by the backticks operator, if one
occurs. Errors are stored in the predefined variable $?
suti
print uptime:
rint s? if $
TIP: Although you probabiy should check $ many programmers just content themse/ves with checking the return value
from the backticks operator, making sure it's not empty like this: unless(command ) print"Error ,T
Let me add one final note: Passing unchecked commands that the user types to
the backtic ks operator is a very bad idea for security rcasons
exec Execute a Program
The big boss appears and says, We have so many products now that the public is
getting confused. We nccd to have onc unified interfacc that, will launch our othcr
programs as appropriate. "You ask, You want me to launch other programs from
mv code?”“ Thats right;” the BB says.“Okay," you say,“ Ill use the exec function.”
The exec function executes a program or system command
exec LIST
exec PRUGRAM LISt
This function executes a program or systcm command and never returns. (If you
want the command to return, use the system function. )That is, this function
replaces your program with another one
The exec function fails and returns false only if the program you call does not
exist. Because exec never returns unless an error occurs, Perl will give you warn
ings if you use the -w switch when there are statements after exec that are not
die. warn or exit statements
1934eC1P5
8/3001,3:15PM
cHapter 1 Built-In Functions: Interprocess Communication
Note that system commands can differ by operating system. The following (rare)
exec call example will work under both windows and unix
exec 'echo Hello
Hejia
The way exec treats its parameters is complex. It works like this in Unix: IfLIST
contains more than one argument (or if lisT is an array with more than one
value), exec calls the system function execvp with that list, treating the first
clement in the list. as the namc of the program to run.
If you pass a single scalar argument (or an array with just one element), Perl
checks for shell mctacharactcrs, which you usc to perforin operations such as
creating pipes. The Unix shell metacharacters are as follows
8;\"|*?~<>^()[]}$nr
If exec finds any metacharacters, the argument is passed to the systems com-
mand shell. If on the other hand. perl finds no shell metacharacters the argu-
ment is split and passed to execvp
In this example, I use the exec function to delete a file using the system unlink
comman
a=( unlink
if(exec(a))die exec call failed: $ 1
In this case, I'm passing the arguments to this function in an array to make sure
the function explicitly realizes that two items appear in the list and cant treat
unlink delete me. txt as a namc of a program and so fail. Passing arguments in
an explicit array like this is often safest when you're using the exec function
Bcar in mind that, as with the bac ks operator;, it's a bad idca for sccurity rca.
sons to pass strings the user types in to the exec function without checking them
system Fork and Run Another Program
Hey, the Novice Programmer says, "Tvc becn using the exec function to cxccutc
another program, and nothing ever came back. How can i get on with the rest of
my code? Easy, you say, dont use exec, which is designed to replace your
program with another onc, usc the system function instcad. Oh, the NP says
e10
1934eC1P5
8/3001,3:15PM
(系统自动生成,下载前可以参看下载内容)
下载文件列表
相关说明
- 本站资源为会员上传分享交流与学习,如有侵犯您的权益,请联系我们删除.
- 本站是交换下载平台,提供交流渠道,下载内容来自于网络,除下载问题外,其它问题请自行百度。
- 本站已设置防盗链,请勿用迅雷、QQ旋风等多线程下载软件下载资源,下载后用WinRAR最新版进行解压.
- 如果您发现内容无法下载,请稍后再次尝试;或者到消费记录里找到下载记录反馈给我们.
- 下载后发现下载的内容跟说明不相乎,请到消费记录里找到下载记录反馈给我们,经确认后退回积分.
- 如下载前有疑问,可以通过点击"提供者"的名字,查看对方的联系方式,联系对方咨询.