私は、perlの親、子、パイプの機能を習得しようとしています。私の目標は、コマンドラインから読み取ってパイプを介して出力する単一のパイプ(双方向ではない)を作成することです。 pidを何度も参照する。お問い合わせ - 親/子供/フォーク/ Pidに関連するループ
これまでコード:
#!/usr/bin/perl -w
use warnings;
use strict;
pipe(READPIPE, WRITEPIPE);
WRITEPIPE->autoflush(1);
STDOUT->autoflush(1);
my $parentpid = $$;
my $childpid = fork() // die "Fork Failed $!\n";
# This is the parent
if ($childpid) {
&parent ($childpid);
close READPIPE;
close WRITEPIPE;
waitpid ($childpid,0);
print "Parent: The child pid with a pid of: $childpid as stopped, and the parent with the pid: $parentpid has stopped.\n";
exit;
}
# This is the child
elsif (defined $childpid) {
&child ($parentpid);
close WRITEPIPE;
}
else {}
sub parent {
while(1){
my $input = <STDIN>;
if ($input eq "\n"){print "Undef- CRTL+C = Quit\n", last;}
else {
print "ParentSub: The parent pid is: ",$parentpid, " and the message being received is: ", $input;
print WRITEPIPE "$input";
print "ParentSub: My parent pid is: $parentpid\n";
print "ParentSub: My child pid is: $childpid\n";
}
}
}
sub child {
while ($line = <READPIPE>){
print "ChildSub: The child pid is: " $childpid,"\n";
print "ChildSub: I got this line from the pipe: ",$line," and the child pid is ",$childpid,"\n";
}
}
電流出力は次のようになります。
Hello World
ParentSub: The parent pid is: 2633 and the message being received is: Hello World
ParentSub: My parent pid is: 2633
ParentSub: My child pid is: 2634
ChildSub: The child pid is: 0
ChildSub: I got this line from the pipe: Hello World
, and the child pid is 0
私はかなり理解していないいくつかの問題に実行しています。
それは、ループは、それが終了したがいない状況での続くproperly-終了しない(そこに入力したキー(別名「\ n」)を打つからの出力の下部後4つの空白行が - それはdoesnの私は
<STDIN>
EXの前に行を追加すると「tはprint "parent: the child pid with ......exit;
に進む。
print "Enter something here: "
を、それが可読性がフラッシュではない作るLOOP-の一環として、その行を繰り返していません。
T情報のハンクス。
信じられないほどの情報。これを読む前に、私は教えている人の助けを借りてプログラムを終えましたが、あなたの答えからどのくらいの情報と理解が得られたのか信じられませんでした。優しい言葉をありがとう@The_Makings_Of_A_Coder –
は、喜んでそれが:)に役立ちます。ドキュメントを徹底的に調べて、慎重に良い知識を集めてください。これは複雑で、ややこしい。頑張って楽しんでね :) – zdim