Perl 使用管道实现进程间的通信
fork()函数:?
作用:进程复制函数。?
用法:$pid=fork(); ? ?
讲解:?
无参数;
当本进程为父进程时返回值为子进程的PID值,当进程为子进程时返回值为0。?
实例:?
分析实例:?
楼上的程序没有父进程与子进程的明显分化,要将它们分开就要靠测试$pid的值,所以对fork()函数的调用来说条件语句是非常重要的,需要通过它们来辨别fork()的返回值。?
注:fork()函数:?
Does a fork(2) system call to create a new process?running the same program at the same point.
fork以后,子进程从fork点开始和主进程运行相同的程序,所以可以通过测试$pid来使主进程和子进程运行不同的程序,
子进程所做的工作结束后应该退出
,不然会继续运行if代码块以后的父进程的程序,这样会运行两次父进程的程序。
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 parentn"; ????????}?else?{ ????????????????#?this?is the child process ????????????????print?"is childn"; ?#子进程退出,会继续运行if一下的程序。 ????????} ????????print?'program after "if"'."n" #会打印两次,一次是父进程打印,一次是子进程打印的。 |
; ? exit 0; ?#子进程退出,不会运行if以后的程序 |
-w my $uid?="test 123"; pipe(CHILD_RDR,?PARENT_WTR; my $pid?; $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;? } |
(PARENT_RDR;? my $pid?==?0this?is child process ????????close PARENT_RDR; ????????print CHILD_WTR?this?is the parent process ????????close CHILD_WTR<PARENT_RDR;? } |
# pipe1 - bidirectional communication using two pipe pairs?
# ? ? ? ? designed for the socketpair-challenged?
use IO::Handle; # thousands of lines just for autoflush :-(?
pipe(PARENT_RDR,CHILD_WTR); # XXX: failure??
pipe(CHILD_RDR,PARENT_WTR); # XXX: failure??
CHILD_WTR->autoflush(1); ?
PARENT_WTR->autoflush(1);?
if ($pid = fork) {?
? #this is parent process?
? close PARENT_RDR; close PARENT_WTR;?
? print CHILD_WTR "Parent Pid $$ is sending thisn";?
? 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 thisn";?
? close PARENT_RDR; close PARENT_WTR;?
? exit;?
}?
#!/usr/bin/perl?-w |
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!