问题陈述--
我使用Perl向用户显示一条消息,并以input.On作为输入的基础,我决定是需要进一步处理还是not.This处理需要很长时间(比如5小时),用户通过登录远程Unix/Linux system.Hence来运行此进程,以确保网络故障不会影响进程;我希望将进程切换到后台。
如何将正在运行的Perl进程切换到后台?
或
如果进程正处于后台运行,是否可以从当前终端(从用户运行进程所在的终端获取用户运行进程的输入)获取用户输入?
OS - Linux变体
发布于 2013-10-04 21:04:52
以下是我上述评论的一个非常非常简单的例子.
#!/usr/bin/perl
use strict;
use warnings;
my $lcnt = 0;
if( !$ARGV[0] ) { # If no ARGS on the command line, get user input
print "How many lines do you want to print?";
chomp( $lcnt = <STDIN> );
if( $lcnt > 0 ) {
# when we are sure we have what we need
# call myself.pl and put it in the background with '&'
my $cmd = "./myself.pl ".$lcnt.' &';
system($cmd);
exit(0);
} else { die "Invalid input!\n"; }
} else { # Otherwise, lets do the processing
$lcnt = $ARGV[0];
for( my $x = 0; $x <= $lcnt; $x++ ) {
my $cmd = "echo 'Printing line: $lcnt' >> /tmp/myself.txt";
system($cmd);
sleep(1);
}
}
exit(0);如果您将它保存到一个名为“myself.pl”的文件中,那么运行它。在命令行没有参数的情况下,脚本将要求您输入一个数字。键入20并按enter键。您将几乎立即看到脚本退出。但如果你快点
tail -f /tmp/myself.txt您将看到后台进程仍在运行,每秒钟向文件打印一条新行。此外,在Linux系统上键入'ps‘命令,应该显示在后台运行的派生进程:
jlb@linux-f7r2:~/test> ps
PID TTY TIME CMD
1243 pts/1 00:00:00 bash
4171 pts/1 00:00:00 myself.pl
4176 pts/1 00:00:00 ps发布于 2013-10-04 17:47:39
是的,您希望在程序完成与用户的交互之后,将其去后台化。不过,我鼓励您使用像Proc::Daemon这样的模块来完成这项工作:正确地做这件事有很多微妙之处。Proc::Daemon很好地描述了它的用法,但是简单的用法可以像
use Proc::Daemon;
# ... finished the interactive stuff
my $pid = Proc::Daemon::Init( { work_dir => '/var/run/my_program' })
exit 0 if ($pid == 0);
die "Error daemonizing, cannot continue: $!\n" if ($! != 0);
# ... now do the background processing
# note that STDOUT and STDERR are no longer connected to the user's terminal!发布于 2013-10-04 16:45:37
如果正确的输入:
#test input
if($inputsuccess) {
if(fork() = 0) {
#child
if(fork() = 0) {
#child
#background processing
}
} else {
wait();
}
}https://stackoverflow.com/questions/19186436
复制相似问题