#!usr/bin/perl -w $pid=fork(); #复制进程,并把返回值附入$pid die "Error:$!\n" unless defined $pid; #制定程序的错误机制,此步可略 if($pid!=0){ #条件选择,测试$pid值,以确定为子进程还是父进程 print"This is a main pid!PID is $$!\n"; #$pid值不等于0,此为父进程(附:$$为保留变量,其值为此进程的PID) }else{ #否则..... print"This is a sub pid!PID is $$!\n"; #$pid值为0,此为子进程 } exit 1;
fork,It clones off a duplicate process identical in virtually every aspect to its parent, including variable settings and open files.(《perl cookbook》)
#!/usr/bin/perl -w
my $pid = fork(); if($pid != 0) { print "is parent\n"; } else { # this is the child process print "is child\n"; #子进程退出,会继续运行if一下的程序。 }
print 'program after "if"'."\n" #会打印两次,一次是父进程打印,一次是子进程打印的。
#!/usr/bin/perl -w
my $pid = fork(); if($pid != 0) { print "is parent\n"; } else { # this is the child process print "is child\n";
exit 0; #子进程退出,不会运行if以后的程序 }
print 'program after "if"'."\n" #只有父进程打印一次
pipe():创建管道对。
格式: pipe(READ,WRITE);
The pipe function creates two connected filehandles, a reader and writer, whereby anything written to the writer can be read from the reader.(摘自《perl cookbook》)
pipe(CHILD_RDR, PARENT_WTR); my $pid = fork(); if($pid != 0) { #this is parent process close CHILD_RDR; print PARENT_WTR "$uid"; } else { # this is the child process close PARENT_WTR; $u =<CHILD_RDR>; print $u;
}
父进程通过子进程获得输入
#!/usr/bin/perl -w my $uid ="test 123";
pipe(PARENT_RDR, CHILD_WTR); my $pid = fork(); if($pid == 0) { #this is child process close PARENT_RDR; print CHILD_WTR "$uid"; } else { # this is the parent process close CHILD_WTR; $u =<PARENT_RDR>; print $u;
#!/usr/bin/perl -w
# pipe1 - bidirectional communication using two pipe pairs
# designed for the socketpair-challenged
use IO::Handle; # thousands of lines just for autoflush :-(
if ($pid = fork) {
#this is parent process
close PARENT_RDR; close PARENT_WTR;
print CHILD_WTR "Parent Pid $$ is sending this\n";
chomp($line = <CHILD_RDR>);
print "Parent Pid $$ just read this: `$line'\n";
close CHILD_RDR; close CHILD_WTR;
waitpid($pid,0);
}
else
{
#this is child process
die "cannot fork: $!" unless defined $pid;
close CHILD_RDR; close CHILD_WTR;
chomp($line = <PARENT_RDR>);
print "Child Pid $$ just read this: `$line'\n";
print PARENT_WTR "Child Pid $$ is sending this\n";
close PARENT_RDR; close PARENT_WTR;
exit;
}
改进版:
#!/usr/bin/perl -w # pipe6 - bidirectional communication using socketpair # "the best ones always go both ways"
use Socket; use IO::Handle; # We say AF_UNIX because although *_LOCAL is the # POSIX 1003.1g form of the constant, many machines # still don't have it. socketpair($child, $parent, AF_UNIX, SOCK_STREAM, PF_UNSPEC) or die "socketpair: $!";
$child->autoflush(1); $parent->autoflush(1);
if($pid = fork) { close $parent; print $child "Parent Pid $$ is sending this\n"; chomp($line =<$child>); print "Parent Pid $$ just read this: '$line'\n"; close $child; waitpid($pid,0); } else { die "cannot fork: $!" unless defined $pid; close $child; chomp($line =<$parent>); print