/
perlipc.pod
executable file
·3449 lines (2575 loc) · 119 KB
/
perlipc.pod
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
=encoding euc-jp
=head1 NAME
=begin original
perlipc - Perl interprocess communication (signals, fifos, pipes, safe subprocesses, sockets, and semaphores)
=end original
perlipc - Perl のプロセス間通信 (シグナル, fifo, パイプ, 安全な副プロセス, ソケット, セマフォ)
=head1 DESCRIPTION
=begin original
The basic IPC facilities of Perl are built out of the good old Unix
signals, named pipes, pipe opens, the Berkeley socket routines, and SysV
IPC calls. Each is used in slightly different situations.
=end original
Perl の基本的な IPC 機能は、古きよき UNIX のシグナル、名前付きパイプ、
パイプ、Berkeley ソケットルーチン、 SysV IPC コールから構成されています。
これら各々ははっきりと異なる状況で使われます。
=head1 Signals
(シグナル)
=begin original
Perl uses a simple signal handling model: the %SIG hash contains names
or references of user-installed signal handlers. These handlers will
be called with an argument which is the name of the signal that
triggered it. A signal may be generated intentionally from a
particular keyboard sequence like control-C or control-Z, sent to you
from another process, or triggered automatically by the kernel when
special events transpire, like a child process exiting, your own process
running out of stack space, or hitting a process file-size limit.
=end original
Perl は単純なシグナルハンドリングモデルを使っています: %SIG という
ハッシュは、ユーザーがインストールしたシグナルハンドラの名前、
もしくはハンドラに対するリファレンスを保持します。
これらのハンドラは、起動されたシグナルの名前を引数として呼び出されます。
シグナルは control-C や control-Z のような特定のキーボードシーケンスで
意識的に生成することもできますし、他のプロセスがシグナルを送ることも
あります; あるいは子プロセスが終了したとか、プロセスがスタックを使いきった、
プロセスのファイルサイズ制限に引っ掛かったといった特殊なイベントが
発生したときに、カーネルが自動的にシグナルを発生させることもあります。
=begin original
For example, to trap an interrupt signal, set up a handler like this:
=end original
例えば割り込みシグナル(interrupt signal)をトラップするには、
以下の例のようにハンドラを設定します:
our $shucks;
sub catch_zap {
my $signame = shift;
$shucks++;
die "Somebody sent me a SIG$signame";
}
$SIG{INT} = __PACKAGE__ . "::catch_zap";
$SIG{INT} = \&catch_zap; # best strategy
=begin original
Prior to Perl 5.8.0 it was necessary to do as little as you possibly
could in your handler; notice how all we do is set a global variable
and then raise an exception. That's because on most systems,
libraries are not re-entrant; particularly, memory allocation and I/O
routines are not. That meant that doing nearly I<anything> in your
handler could in theory trigger a memory fault and subsequent core
dump - see L</Deferred Signals (Safe Signals)> below.
=end original
Perl 5.8.0 以前では、自分のハンドラの中を使うことができます;
私たちが認識していることは、グローバル変数に設定した後で例外を
引き起こすということだけであることに注意してください。
これは、ほとんどのシステム上ではライブラリ、とくにメモリ割り付けや
入出力に関するものは再入可能ではないためです。
これは、あなたのハンドラ内のほとんど I<あらゆること> が理論的には
メモリフォールトやそれに続くコアダンブを引き起こす可能性が
あるということです - 以下の L</Deferred Signals (Safe Signals)> を
参照してください。
=begin original
The names of the signals are the ones listed out by C<kill -l> on your
system, or you can retrieve them using the CPAN module L<IPC::Signal>.
=end original
あなたの使っているシステムにおけるシグナルの名称は C<kill -l> によって
リストアップされます; あるいは CPAN モジュール L<IPC::Signal> から
取得することもできます。
=begin original
You may also choose to assign the strings C<"IGNORE"> or C<"DEFAULT"> as
the handler, in which case Perl will try to discard the signal or do the
default thing.
=end original
ハンドラとして C<"IGNORE"> や C<"DEFAULT"> といった文字列を代入することも
選択できます; これらのハンドラは、perl がシグナルを破棄させるようにしたり
デフォルトの動作を行うようにさせるものです。
=begin original
On most Unix platforms, the C<CHLD> (sometimes also known as C<CLD>) signal
has special behavior with respect to a value of C<"IGNORE">.
Setting C<$SIG{CHLD}> to C<"IGNORE"> on such a platform has the effect of
not creating zombie processes when the parent process fails to C<wait()>
on its child processes (i.e., child processes are automatically reaped).
Calling C<wait()> with C<$SIG{CHLD}> set to C<"IGNORE"> usually returns
C<-1> on such platforms.
=end original
ほとんどの UNIX プラットフォームでは、C<CHLD>(C<CLD> の場合もあり)
シグナルは C<"IGNORE"> の値に対応するような特別な振る舞いをします。
そのようなプラットフォームでは C<"IGNORE"> に C<$SIG{CHLD}> を
設定することによって、親プロセスが C<wait()> に失敗したようなときに
ゾンビプロセスができることを防ぎます(子プロセスは自動的に
刈り取られます)。
C<$SIG{CHLD}> を C<"IGNORE"> を設定して C<wait()> を呼び出すことによって、
このようなプラットフォームでは C<-1> が通常返されます。
=begin original
Some signals can be neither trapped nor ignored, such as the KILL and STOP
(but not the TSTP) signals. Note that ignoring signals makes them disappear.
If you only want them blocked temporarily without them getting lost you'll
have to use POSIX' sigprocmask.
=end original
KILL シグナルや STOP シグナル(TSTP ではない)のような幾つかのシグナルは、
トラップすることも無視することもできません。
見視されるシグナルはこれを消すことに注意してください。
失うことなく一時的にブロックしたいだけなら、POSIX の sigprocmask を使う
必要があります。
=begin original
Sending a signal to a negative process ID means that you send the signal
to the entire Unix process group. This code sends a hang-up signal to all
processes in the current process group, and also sets $SIG{HUP} to C<"IGNORE">
so it doesn't kill itself:
=end original
負のプロセス ID に対してシグナルを送ることは、UNIX プロセスグループ
全体にシグナルを送ることになります。
以下のコードは、カレントのプロセスグループに属する全てのプロセスに
hang-up シグナルを送出します; そして、$SIG{HUP} に IGNORE を設定するので、
自分自身を kill することはありません:
# block scope for local
{
local $SIG{HUP} = "IGNORE";
kill HUP => -$$;
# snazzy writing of: kill("HUP", -$$)
}
=begin original
Another interesting signal to send is signal number zero. This doesn't
actually affect a child process, but instead checks whether it's alive
or has changed its UIDs.
=end original
この他の興味深いシグナルは、シグナル番号 0 です。
これは実際には子プロセスに影響を及ぼすことはありませんが、UID が
生きているのか、あるいは変更されたのかのチェックを行います。
unless (kill 0 => $kid_pid) {
warn "something wicked happened to $kid_pid";
}
=begin original
Signal number zero may fail because you lack permission to send the
signal when directed at a process whose real or saved UID is not
identical to the real or effective UID of the sending process, even
though the process is alive. You may be able to determine the cause of
failure using C<$!> or C<%!>.
=end original
送り先のプロセスの実または保存 UID が、送り元の実または保存 UID と
同じではない場合、たとえプロセスが生きていても、シグナルを送る権限が
ないので、シグナル番号 0 は失敗します。
失敗の原因は、C<$!> や C<%!> を使って決定できます。
unless (kill(0 => $pid) || $!{EPERM}) {
warn "$pid looks dead";
}
=begin original
You might also want to employ anonymous functions for simple signal
handlers:
=end original
単純なシグナルハンドラには無名関数を使いたくなるかもしれません:
$SIG{INT} = sub { die "\nOutta here!\n" };
=begin original
SIGCHLD handlers require some special care. If a second child dies
while in the signal handler caused by the first death, we won't get
another signal. So must loop here else we will leave the unreaped child
as a zombie. And the next time two children die we get another zombie.
And so on.
=end original
SIGCHLD ハンドラは特別な対応が必要です。
一つ目の子が死んだことによって起動されたシグナルハンドラの実行中に
二つ目の子が死ぬと、もう一つのシグナルは受け取れません。
従ってここでループしなければなりません; さもなければ処理されない子が
ゾンビとして残ります。
そして次に二つの子が死ぬともう一つのゾンビが発生します。
以下同様です。
use POSIX ":sys_wait_h";
$SIG{CHLD} = sub {
while ((my $child = waitpid(-1, WNOHANG)) > 0) {
$Kid_Status{$child} = $?;
}
};
# do something that forks...
=begin original
Be careful: qx(), system(), and some modules for calling external commands
do a fork(), then wait() for the result. Thus, your signal handler
will be called. Because wait() was already called by system() or qx(),
the wait() in the signal handler will see no more zombies and will
therefore block.
=end original
注意してください: qx(), system() および外部コマンドを呼び出す一部の
モジュールは fork() してから結果を wait() します。
従って、シグナルハンドラが呼び出されます。
なぜなら wait() は既に system() や qx() によって呼び出されているので、
シグナルハンドラ内の wait() はゾンビを見ることはなく、従ってブロックします。
=begin original
The best way to prevent this issue is to use waitpid(), as in the following
example:
=end original
この問題を避ける最良の方法は waitpid() を使うことで、以下の例のようにします:
use POSIX ":sys_wait_h"; # for nonblocking read
my %children;
$SIG{CHLD} = sub {
# don't change $! and $? outside handler
local ($!, $?);
my $pid = waitpid(-1, WNOHANG);
return if $pid == -1;
return unless defined $children{$pid};
delete $children{$pid};
cleanup_child($pid, $?);
};
while (1) {
my $pid = fork();
die "cannot fork" unless defined $pid;
if ($pid == 0) {
# ...
exit 0;
} else {
$children{$pid}=1;
# ...
system($command);
# ...
}
}
=begin original
Signal handling is also used for timeouts in Unix. While safely
protected within an C<eval{}> block, you set a signal handler to trap
alarm signals and then schedule to have one delivered to you in some
number of seconds. Then try your blocking operation, clearing the alarm
when it's done but not before you've exited your C<eval{}> block. If it
goes off, you'll use die() to jump out of the block.
=end original
シグナルハンドリングは Unix でのタイムアウトでも使われます。
C<eval{}> ブロックの中では安全に保護される一方、シグナルをトラップして、
数秒後に配達されるように予定するためにアラームのシグナルハンドラを設定します。
それからブロックされる処理を試して、それが終了した後 C<eval{}> ブロックが
終了する前にアラームをクリアします。
停止したときは、ブロックから出るために die() を使います。
=begin original
Here's an example:
=end original
例を挙げましょう:
my $ALARM_EXCEPTION = "alarm clock restart";
eval {
local $SIG{ALRM} = sub { die $ALARM_EXCEPTION };
alarm 10;
flock(FH, 2) # blocking write lock
|| die "cannot flock: $!";
alarm 0;
};
if ($@ && $@ !~ quotemeta($ALARM_EXCEPTION)) { die }
=begin original
If the operation being timed out is system() or qx(), this technique
is liable to generate zombies. If this matters to you, you'll
need to do your own fork() and exec(), and kill the errant child process.
=end original
時間切れを起こした操作が system() か qx() なら、このテクニックはゾンビを
生成する傾向があります。
もしそれが問題なら、自力で fork() と exec() を行って、エラーの起きた
子プロセスを kill する必要があるでしょう。
=begin original
For more complex signal handling, you might see the standard POSIX
module. Lamentably, this is almost entirely undocumented, but
the F<t/lib/posix.t> file from the Perl source distribution has some
examples in it.
=end original
より複雑なシグナル処理のためには、標準の POSIX モジュールを確かめると
よいかもしれません。
嘆かわしいことにこれはほとんどアンドキュメントな状態ですが、Perl の
ソース配布キットにある F<t/lib/posix.t> というファイルには幾つかの
サンプルがあります。
=head2 Handling the SIGHUP Signal in Daemons
(デーモンで SIGHUP シグナルを扱う)
=begin original
A process that usually starts when the system boots and shuts down
when the system is shut down is called a daemon (Disk And Execution
MONitor). If a daemon process has a configuration file which is
modified after the process has been started, there should be a way to
tell that process to reread its configuration file without stopping
the process. Many daemons provide this mechanism using a C<SIGHUP>
signal handler. When you want to tell the daemon to reread the file,
simply send it the C<SIGHUP> signal.
=end original
普通システムブート時に起動し、システムシャットダウン時に終了するプロセスの
ことをデーモン(daemon: Disk And Execution MONitor)と呼びます。
もしデーモンプロセスに設定ファイルがあり、それがプロセスが開始してから
変更された場合、プロセスを止めることなく、プロセスに設定ファイルを
再読み込みすることを知らせる方法があるべきです。
多くのデーモンはこの機構を C<SIGHUP> シグナルハンドラを使って
提供しています。
デーモンにファイルを再読み込みしてほしい場合、単にデーモンに
C<SIGHUP> シグナルを送ります。
=begin original
The following example implements a simple daemon, which restarts
itself every time the C<SIGHUP> signal is received. The actual code is
located in the subroutine C<code()>, which just prints some debugging
info to show that it works; it should be replaced with the real code.
=end original
以下の例は、C<SIGHUP> を受け取る毎に再起動するという単純なデーモンを
実装しています。
実際のコードはサブルーチン C<code()> に置かれていて、どのように動作するかを
示すために単にデバッグ情報を出力します; これは実際のコードと
置き換えられます。
#!/usr/bin/perl -w
use POSIX ();
use FindBin ();
use File::Basename ();
use File::Spec::Functions;
$| = 1;
# make the daemon cross-platform, so exec always calls the script
# itself with the right path, no matter how the script was invoked.
my $script = File::Basename::basename($0);
my $SELF = catfile($FindBin::Bin, $script);
# POSIX unmasks the sigprocmask properly
$SIG{HUP} = sub {
print "got SIGHUP\n";
exec($SELF, @ARGV) || die "$0: couldn't restart: $!";
};
code();
sub code {
print "PID: $$\n";
print "ARGV: @ARGV\n";
my $count = 0;
while (++$count) {
sleep 2;
print "$count\n";
}
}
=head2 Deferred Signals (Safe Signals)
(保留シグナル(安全なシグナル))
=begin original
Before Perl 5.8.0, installing Perl code to deal with signals exposed you to
danger from two things. First, few system library functions are
re-entrant. If the signal interrupts while Perl is executing one function
(like malloc(3) or printf(3)), and your signal handler then calls the same
function again, you could get unpredictable behavior--often, a core dump.
Second, Perl isn't itself re-entrant at the lowest levels. If the signal
interrupts Perl while Perl is changing its own internal data structures,
similarly unpredictable behavior may result.
=end original
Perl 5.8.0 以前では、シグナルを取り扱う Perl プログラムを
インストールすることによって、あなたは二つの危険性に直面することに
なりました。
第一に、再入可能なライブラリ関数を備えたシステムは数少ないこと。
Perl がある関数(malloc(3) や printf(3) など)を実行中にシグナル割り込みが
あったとすると、あなたのシグナルハンドラは同じ関数を
再度呼び出し、結果として予測のつかない動作になる可能性があります。
第二に、Perl 自身も最低レベルにおいては再入可能に
なっていないということです。
Perl が自分の内部構造を操作しているときにシグナル割り込みが
あったとすると、これもまた予測のつかない動作になるでしょう。
=begin original
There were two things you could do, knowing this: be paranoid or be
pragmatic. The paranoid approach was to do as little as possible in your
signal handler. Set an existing integer variable that already has a
value, and return. This doesn't help you if you're in a slow system call,
which will just restart. That means you have to C<die> to longjmp(3) out
of the handler. Even this is a little cavalier for the true paranoiac,
who avoids C<die> in a handler because the system I<is> out to get you.
The pragmatic approach was to say "I know the risks, but prefer the
convenience", and to do anything you wanted in your signal handler,
and be prepared to clean up core dumps now and again.
=end original
あなたの取りうる手段が二つありました:
偏執狂的になるか現実的になるかです。
偏執狂的アプローチは、あなたのシグナルハンドラの中でできるだけ
少ないことを行うというものでした。
既に値をもって存在している整数変数に値を設定してリターンします。
これは単にリスタートするような遅いシステムコールの中にいるときには
助けになりません。
これはつまり、ハンドラの外に longjmp(3) するには C<die> する必要が
あるということです。
これは本当の偏執狂というのにはちょっとおおげさですが、ハンドラ中で
C<die> を排除します。
現実的なアプローチは「リスクがあるのは分かってるけどさ、便利なら
いいじゃない」というもので、シグナルハンドラ中で行いたいことを
全て行い、コアダンプを掃除する準備をしてから再度行うというものでした。
=begin original
Perl 5.8.0 and later avoid these problems by "deferring" signals. That is,
when the signal is delivered to the process by the system (to the C code
that implements Perl) a flag is set, and the handler returns immediately.
Then at strategic "safe" points in the Perl interpreter (e.g. when it is
about to execute a new opcode) the flags are checked and the Perl level
handler from %SIG is executed. The "deferred" scheme allows much more
flexibility in the coding of signal handlers as we know the Perl
interpreter is in a safe state, and that we are not in a system library
function when the handler is called. However the implementation does
differ from previous Perls in the following ways:
=end original
Perl 5.8.0 以降では、「保留」シグナルによってこの問題を回避します。
これは、システムによってシグナルが (Perl を実装している C コードに)
配送されると、フラグをセットして、ハンドラは直ちに返ります。
それから、Perl インタプリタの戦略的に「安全な」地点
(例えば、新しいオペコードを実行しようとしている時点) で、
フラグをチェックして、%SIG の Perl レベルハンドラを実行します。
「保留」スキームは、Perl インタプリタが安全な状態にあって、ハンドラが
呼び出されたときにシステムライブラリの中ではないことが分かっているので、
シグナルハンドラのコーディングが遥かに柔軟になります。
しかし、実装は以下の方向で以前の Perl と異なります:
=over 4
=item Long-running opcodes
(長時間実行されるオペコード)
=begin original
As the Perl interpreter looks at signal flags only when it is about
to execute a new opcode, a signal that arrives during a long-running
opcode (e.g. a regular expression operation on a very large string) will
not be seen until the current opcode completes.
=end original
Perl インタプリタは、もし長時間実行されるオペコード
(例えばとても長い文字列での正規表現操作)の途中でシグナルが
到着すると、新しいオペコードを実行しようとする時にのみシグナルフラグを
見るので、シグナルは現在のオペコードが完了するまで現れません。
=begin original
If a signal of any given type fires multiple times during an opcode
(such as from a fine-grained timer), the handler for that signal will
be called only once, after the opcode completes; all other
instances will be discarded. Furthermore, if your system's signal queue
gets flooded to the point that there are signals that have been raised
but not yet caught (and thus not deferred) at the time an opcode
completes, those signals may well be caught and deferred during
subsequent opcodes, with sometimes surprising results. For example, you
may see alarms delivered even after calling C<alarm(0)> as the latter
stops the raising of alarms but does not cancel the delivery of alarms
raised but not yet caught. Do not depend on the behaviors described in
this paragraph as they are side effects of the current implementation and
may change in future versions of Perl.
=end original
もしどのような種類のシグナルでも(例えば高精度のタイマーから)
1 つのオペコードの間に複数回発生した場合、そのシグナルのハンドラは
オペコードの完了後 1 度しか呼び出されません; その他の実体は破棄されます。
さらに、システムのシグナルキューがあふれたために
あるオペコードが完了時に、発生したけれどもまだ捕捉されていない
(従ってまだ保留されていない)シグナルがあると
これらのシグナルが引き続くオペコードの間捕捉および保留され、時々
驚くべき結果となることがあります。
例えば、C<alarm(0)> はアラームの発生を止めますが、
発生したけれどもまだ捕捉していないアラームの配達がキャンセルしないので、
C<alarm(0)> を呼び出した後にもアラームが配送されることがあります。
これは現在の実装の副作用であり、将来のバージョンの Perl では
変更されるかもしれないので、この段落に記述された振る舞いに依存しては
いけません。
=item Interrupting IO
(I/O 割り込み)
=begin original
When a signal is delivered (e.g., SIGINT from a control-C) the operating
system breaks into IO operations like I<read>(2), which is used to
implement Perl's readline() function, the C<< <> >> operator. On older
Perls the handler was called immediately (and as C<read> is not "unsafe",
this worked well). With the "deferred" scheme the handler is I<not> called
immediately, and if Perl is using the system's C<stdio> library that
library may restart the C<read> without returning to Perl to give it a
chance to call the %SIG handler. If this happens on your system the
solution is to use the C<:perlio> layer to do IO--at least on those handles
that you want to be able to break into with signals. (The C<:perlio> layer
checks the signal flags and calls %SIG handlers before resuming IO
operation.)
=end original
(例えば control-C からの SIGINT で) シグナルが配送されると、OS は Perl の
readline() 関数と C<< <> >> 演算子の実装で使われている I<read>(2) のような
I/O 操作を中断します。
古い Perl ではハンドラをすぐに呼び出します
(そして C<read> は「安全ではない」ことはないので、うまく動きます)。
「保留」スキームではハンドラはすぐには I<呼び出されず>、
もし Perl がシステムの C<stdio> ライブラリを使っていると、ライブラリは
Perl に返って %SIG ハンドラを呼び出しする機会なしに C<read> を再起動します。
もしこれが起きた場合、解決法は、I/O を行うときに--
少なくともシグナルで中断できるようにしたいハンドルで--
C<:perlio> 層を使うことです。
(C<:perlio> 層はシグナルフラグをチェックして、I/O 操作を続行する前に
%SIG ハンドラを呼び出します。)
=begin original
The default in Perl 5.8.0 and later is to automatically use
the C<:perlio> layer.
=end original
Perl 5.7.3 以降ではデフォルトでは自動的に C<:perlio> 層が使われます。
=begin original
Note that it is not advisable to access a file handle within a signal
handler where that signal has interrupted an I/O operation on that same
handle. While perl will at least try hard not to crash, there are no
guarantees of data integrity; for example, some data might get dropped or
written twice.
=end original
シグナルがファイルハンドルに対する I/O 操作を中断した場所で、シグナル
ハンドラの中のそのハンドラをアクセスするのは勧められません。
perl は少なくともクラッシュはしないように努力する一方、データの
完全性については保証しないので、一部のデータは欠落したり 2 回
書かれたりするかもしれません。
=begin original
Some networking library functions like gethostbyname() are known to have
their own implementations of timeouts which may conflict with your
timeouts. If you have problems with such functions, try using the POSIX
sigaction() function, which bypasses Perl safe signals. Be warned that
this does subject you to possible memory corruption, as described above.
=end original
gethostbyname() のようなネットワークライブラリ関数は独自のタイムアウト
実装を持っていることが知られているので、あなたのタイムアウトと
競合するかもしれません。
もしこのような関数で問題が起きた場合は、Perl の安全なシグナルを回避する
POSIX sigaction() 関数を試すことができます。
これは上述の、メモリ破壊の可能性があるということに注意してください。
=begin original
Instead of setting C<$SIG{ALRM}>:
=end original
C<$SIG{ALRM}> をセットする代わりに:
local $SIG{ALRM} = sub { die "alarm" };
=begin original
try something like the following:
=end original
以下のようなことを試してみてください:
use POSIX qw(SIGALRM);
POSIX::sigaction(SIGALRM, POSIX::SigAction->new(sub { die "alarm" }))
|| die "Error setting SIGALRM handler: $!\n";
=begin original
Another way to disable the safe signal behavior locally is to use
the C<Perl::Unsafe::Signals> module from CPAN, which affects
all signals.
=end original
安全なシグナルの振る舞いを局所的に無効にするもう一つの方法は
CPAN の C<Perl::Unsafe::Signals> モジュールを使うことです;
これは全てのシグナルに影響を与えます。
=item Restartable system calls
(再起動可能なシステムコール)
=begin original
On systems that supported it, older versions of Perl used the
SA_RESTART flag when installing %SIG handlers. This meant that
restartable system calls would continue rather than returning when
a signal arrived. In order to deliver deferred signals promptly,
Perl 5.8.0 and later do I<not> use SA_RESTART. Consequently,
restartable system calls can fail (with $! set to C<EINTR>) in places
where they previously would have succeeded.
=end original
これに対応しているシステムでは、より古いバージョンの Perl では %SIG
ハンドラを設定するときに SA_RESTART フラグを使います。
これは、再起動可能なシステムコールではシグナルが配送されたときに
戻るのではなく続行することを意味します。
保留シグナルを素早く配送するために、
Perl 5.8.0 以降では SA_RESTART を I<使っていません>。
結果として、再起動可能なシステムコールは、いままで成功していたところでも
($! に C<EINTR> をセットして) 失敗することがあります。
=begin original
The default C<:perlio> layer retries C<read>, C<write>
and C<close> as described above; interrupted C<wait> and
C<waitpid> calls will always be retried.
=end original
デフォルトの C<:perlio> 層では C<read>, C<write>, C<close> は上述したように
再試行します; 中断された C<wait> と C<waitpid> の呼び出しは常に
再試行されます。
=item Signals as "faults"
(「障害」としてのシグナル)
=begin original
Certain signals like SEGV, ILL, and BUS are generated by virtual memory
addressing errors and similar "faults". These are normally fatal: there is
little a Perl-level handler can do with them. So Perl delivers them
immediately rather than attempting to defer them.
=end original
SEGV, ILL, BUS のようなシグナルは、仮想メモリアドレッシングエラーや
似たような「障害」の結果として生成されます。
これらは普通致命的です: Perl レベルのハンドラができることはほとんど
ありません。
なので Perl はこれらを保留しようとせず、直ちに配送します。
=item Signals triggered by operating system state
(OS の状態によって発生するシグナル)
=begin original
On some operating systems certain signal handlers are supposed to "do
something" before returning. One example can be CHLD or CLD, which
indicates a child process has completed. On some operating systems the
signal handler is expected to C<wait> for the completed child
process. On such systems the deferred signal scheme will not work for
those signals: it does not do the C<wait>. Again the failure will
look like a loop as the operating system will reissue the signal because
there are completed child processes that have not yet been C<wait>ed for.
=end original
OS によっては、ある種のシグナルハンドラは返る前に「何かをする」ことに
なっているものもあります。
1 つの例としては CHLD や CLD で、子プロセスが完了したことを示しています。
OS によっては、シグナルハンドルは完了した子プロセスのために
C<wait> することを想定されているものもあります。
このようなシステムでは保留シグナルスキームはこれらのシグナルでは
動作しません: C<wait> しません。
再び、問題は、まだ C<wait> していない完了した子プロセスがあるかのように
シグナルが再び発生することでループのように見えます。
=back
=begin original
If you want the old signal behavior back despite possible
memory corruption, set the environment variable C<PERL_SIGNALS> to
C<"unsafe">. This feature first appeared in Perl 5.8.1.
=end original
もし、メモリ破壊の可能性にもかかわらず、古いシグナルの振る舞いが
ほしいなら、環境変数 C<PERL_SIGNALS> を C<"unsafe"> に設定してください。
この機能は Perl 5.8.1 に現れました。
=head1 Named Pipes
(名前付きパイプ)
=begin original
A named pipe (often referred to as a FIFO) is an old Unix IPC
mechanism for processes communicating on the same machine. It works
just like regular anonymous pipes, except that the
processes rendezvous using a filename and need not be related.
=end original
名前付きパイプ(しばしば FIFO として参照されます)は、同じマシン上での
プロセス間通信のための古い UNIX IPC 機構です。
これは通常の無名パイプと同様に動作しますが、ファイル名を使って
プロセスのランデブーが行われ、関連づける必要がないという点が異なります。
=begin original
To create a named pipe, use the C<POSIX::mkfifo()> function.
=end original
名前付きパイプを生成するには、C<POSIX::mkfifo()> 関数を使ってください。
use POSIX qw(mkfifo);
mkfifo($path, 0700) || die "mkfifo $path failed: $!";
=begin original
You can also use the Unix command mknod(1), or on some
systems, mkfifo(1). These may not be in your normal path, though.
=end original
一部のシステムでは Unix コマンド mknod(1) か、システムによっては
mkfifo(1) を使えます。
しかしこれらはあなたの通常パス(normal path)に置くことはできません。
# system return val is backwards, so && not ||
#
$ENV{PATH} .= ":/etc:/usr/etc";
if ( system("mknod", $path, "p")
&& system("mkfifo", $path) )
{
die "mk{nod,fifo} $path failed";
}
=begin original
A fifo is convenient when you want to connect a process to an unrelated
one. When you open a fifo, the program will block until there's something
on the other end.
=end original
fifo は、あるプロセスをそれとは関係ない別のプロセスに接続したいときに
便利です。
fifo をオープンしたとき、プログラムはもう一方の端点に何かが
置かれるまでブロックされます。
=begin original
For example, let's say you'd like to have your F<.signature> file be a
named pipe that has a Perl program on the other end. Now every time any
program (like a mailer, news reader, finger program, etc.) tries to read
from that file, the reading program will read the new signature from your
program. We'll use the pipe-checking file-test operator, B<-p>, to find
out whether anyone (or anything) has accidentally removed our fifo.
=end original
たとえば、F<.signature> というファイルを、もう一方の端点に Perl
プログラムが置かれている名前付きパイプに接続したいとしましょう。
このとき、任意のプログラムが任意の時点で(メイラー、ニューズリーダー、
finger プログラムなどのように)そのファイルを読み出そうとしますから、
読み出しプログラムはあなたのプログラムから新しいシグネチャを読み込みます。
誰か(もしくは何か)が間違って私たちのfifoを削除したりしないかどうかを
監視するために B<-p> という pipe-cheching ファイルテスト演算子を使用します。
chdir(); # go home
my $FIFO = ".signature";
while (1) {
unless (-p $FIFO) {
unlink $FIFO; # discard any failure, will catch later
require POSIX; # delayed loading of heavy module
POSIX::mkfifo($FIFO, 0700)
|| die "can't mkfifo $FIFO: $!";
}
# next line blocks till there's a reader
open (FIFO, "> $FIFO") || die "can't open $FIFO: $!";
print FIFO "John Smith (smith\@host.org)\n", `fortune -s`;
close(FIFO) || die "can't close $FIFO: $!";
sleep 2; # to avoid dup signals
}
=head1 Using open() for IPC
(IPC のために open() を使う)
=begin original
Perl's basic open() statement can also be used for unidirectional
interprocess communication by either appending or prepending a pipe
symbol to the second argument to open(). Here's how to start
something up in a child process you intend to write to:
=end original
Perlの open() 文は、その第二引数でパイプシンボルを前置するか末尾に
付加することによって、一方向のプロセス間通信のために使うことができます。
以下の例は、書き込みを行いたい子プロセスを起動させるやり方です:
open(SPOOLER, "| cat -v | lpr -h 2>/dev/null")
|| die "can't fork: $!";
local $SIG{PIPE} = sub { die "spooler pipe broke" };
print SPOOLER "stuff\n";
close SPOOLER || die "bad spool: $! $?";
=begin original
And here's how to start up a child process you intend to read from:
=end original
そして以下の例はそこから読み込みを行いたい子プロセスを起動する方法です:
open(STATUS, "netstat -an 2>&1 |")
|| die "can't fork: $!";
while (<STATUS>) {
next if /^(tcp|udp)/;
print;
}
close STATUS || die "bad netstat: $! $?";
=begin original
If one can be sure that a particular program is a Perl script expecting
filenames in @ARGV, the clever programmer can write something like this:
=end original
特定のプログラムの一つが @ARGV にあるファイル名を期待している
Perl スクリプトであっていいのなら、賢いプログラマは以下のように
書くこともできます:
% program f1 "cmd1|" - f2 "cmd2|" f3 < tmpfile
=begin original
and no matter which sort of shell it's called from, the Perl program will
read from the file F<f1>, the process F<cmd1>, standard input (F<tmpfile>
in this case), the F<f2> file, the F<cmd2> command, and finally the F<f3>
file. Pretty nifty, eh?
=end original
そしてそれを呼んだシェルには関係なく、この Perl プログラムは F<f1> という
ファイル、F<cmd1> というプロセス、標準入力(この例では F<tmpfile>)、
F<f2> というファイル、F<cmd2> というコマンド、F<f3> というファイルから
読み込みを行います。
すごくいいよね?
=begin original
You might notice that you could use backticks for much the
same effect as opening a pipe for reading:
=end original
読み込みのためのパイプを開くために、逆クォートを使って同じことが
できることに気がつくかもしれません:
print grep { !/^(tcp|udp)/ } `netstat -an 2>&1`;
die "bad netstatus ($?)" if $?;
=begin original
While this is true on the surface, it's much more efficient to process the
file one line or record at a time because then you don't have to read the
whole thing into memory at once. It also gives you finer control of the
whole process, letting you kill off the child process early if you'd like.
=end original
その推測は表面的には正しいことのように見えるかも知れませんが、一度に
メモリにすべてを読み込む必要がないので、一度にファイルの一行や
一レコードを処理するには(最初の例のほうが)より効率的なのです。
同様にプロセス全体の制御を与えるので、あなたが望めば早い時期に
子プロセスを kill することができます。
=begin original
Be careful to check the return values from both open() and close(). If
you're I<writing> to a pipe, you should also trap SIGPIPE. Otherwise,
think of what happens when you start up a pipe to a command that doesn't
exist: the open() will in all likelihood succeed (it only reflects the
fork()'s success), but then your output will fail--spectacularly. Perl
can't know whether the command worked, because your command is actually
running in a separate process whose exec() might have failed. Therefore,
while readers of bogus commands return just a quick EOF, writers
to bogus commands will get hit with a signal, which they'd best be prepared
to handle. Consider:
=end original
open() と close() の戻り値をチェックするときは注意してください。
パイプに対して B<書き込み> をしたのなら、SIGPIPE をトラップすべきです。
そうしなければ、存在しないコマンドに対するパイプを起動したときに
起こることについて考え込むことになるでしょう: open() はほとんどの
場合成功すると見込まれるでしょうが(これは fork() の成功だけを
反映します)、あなたの出力はその後で壮観に(spectacularly)失敗するでしょう。