加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl多任务问题

发布时间:2020-12-15 23:21:38 所属栏目:大数据 来源:网络整理
导读:我已经完成了我之前使用perl线程的多线程程序,它可以在我的系统上运行.问题是,在某些需要运行的系统上,线程支持不会编译到perl中,我无法安装其他软件包.因此,我需要使用除线程之外的其他东西,我正在将代码移动到使用fork().这可以在我的 Windows系统上启动子
我已经完成了我之前使用perl线程的多线程程序,它可以在我的系统上运行.问题是,在某些需要运行的系统上,线程支持不会编译到perl中,我无法安装其他软件包.因此,我需要使用除线程之外的其他东西,我正在将代码移动到使用fork().这可以在我的 Windows系统上启动子任务.

一些问题:

>如何确定子进程何时退出?我在线程数低于某个值时创建了新线程,我需要跟踪正在运行的线程数.对于进程,如何知道何时退出,以便我可以跟踪当时有多少存在,在创建一个计数器时递增计数器,在一个计数器退出时递减计数器?
>在子进程中由父进程打开时,使用OPEN获取的句柄的文件I / O是?我需要为每个子进程附加一个文件,这在unix上也是安全的.
>有没有替代fork和线程?我尝试使用Parallel :: ForkManager,但是我的系统上没有安装(使用Parallel :: ForkManager;出错)我绝对要求我的perl脚本可以在所有unix / windows系统上运行而无需安装任何其他模块.

解决方法

典型用法:

use POSIX ':sys_wait_h';    # for &WNOHANG

# how to create a new background process
$pid = fork();
if (!defined $pid) { die "fork() failed!" }
if ($pid == 0) { # child
    # ... do stuff in background ...
    exit 0;      # don't forget to exit or die from the child process
} 
# else this is the parent,$pid contains process id of child process
# ... do stuff in foreground ...

# how to tell if a process is finished
# also see  perldoc perlipc
$pid = waitpid -1,0;           # blocking wait for any process
$pid = wait;                    # blocking wait for any process
$pid = waitpid $mypid,0;       # blocking wait for process $mypid
# after blocking wait/waitpid
if ($pid == -1) {
    print "All child processes are finished.n";
} else {
    print "Process $pid is finished.n";
    print "The exit status of process $pid was $?n";
}

$pid = waitpid -1,&WNOHANG;    # non-blocking wait for any process
$pid = waitpid $mypid,0;       # blocking wait for process $mypid
if ($pid == -1) {
    print "No child processes have finished since last wait/waitpid call.n";
} else {
    print "Process $pid is finished.n";
    print "The exit status of process $pid was $?n";
}

# terminating a process - see  perldoc -f kill  or  perldoc perlipc
# this can be flaky on Windows
kill 'INT',$pid;               # send SIGINT to process $pid

perldoc -f fork,waitpid,wait,killperlipc中的Gory细节.关于为SIGCHLD事件设置处理程序的perlipc中的内容应该特别有用,尽管在Windows上不支持.

分叉进程的I / O在Unix和Windows上通常是安全的.文件描述符是共享的,所以对于这样的事情

open X,">",$file;
if (fork() == 0) {  # in child
    print X "Childn"; 
    close X;
    exit 0;
}
# in parent
sleep 1;
print X "Parentn";
close X;

子进程和父进程都会成功写入同一个文件(但要注意输出缓冲).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读