| Forks-Super documentation | view source | Contained in the Forks-Super distribution. |
$n = Forks::Super::Job::count_active_processes() Forks::Super module,
and not processes that may have been created outside the
Forks::Super framework, say, by an explicit call to
CORE::fork(), a call like system("./myTask.sh &"),
or a form of Perl's open function that launches an
external command.
Forks::Super::Job - object representing a background task
0.52
use Forks::Super;
$pid = Forks::Super::fork( \%options ); # see Forks::Super
$job = Forks::Super::Job::get($pid);
$job = Forks::Super::Job::getByName($name);
print "Current job state is $job->{state}\n";
print "Job was created at ", scalar localtime($job->{created}), "\n";
See "OVERLOADING".
use Forks::Super 'overload';
$job = Forks::Super::fork( \%options );
print "Process id of new job is $job\n";
print "Current state is ", $job->state, "\n";
waitpid $job, 0;
print "Exit status was ", $job->status, "\n";
Calls to Forks::Super::fork() that successfully spawn a child process or
create a deferred job (see "Deferred processes" in Forks::Super) will cause
a Forks::Super::Job instance to be created to track the job's state.
For many uses of fork(), it will not be necessary to query the state of
a background job. But access to these objects is provided for users who
want to exercise even greater control over their use of background
processes.
Calls to Forks::Super::fork() that fail (return undef or small negative
numbers) generally do not cause a new Forks::Super::Job instance
to be created.
Use the Forks::Super::Job::get or Forks::Super::Job::getByName
methods to obtain a Forks::Super::Job object for
examination. The Forks::Super::Job::get method takes a process ID or
job ID as an input (a value that may have been returned from a previous
call to Forks::Super::fork() and returns a reference to a
Forks::Super::Job object, or undef if the process ID or job ID
was not associated with any known Job object. The
Forks::Super::Job::getByName looks up job objects by the
name parameter that may have been passed
in the Forks::Super::fork() call.
A Forks::Super::Job object has many attributes, some of which may
be of interest to an end-user. Most of these should not be overwritten.
Process ID or job ID. For deferred processes, this will be a unique large negative number (a job ID). For processes that were not deferred, this valud is the process ID of the child process that performed this job's task.
The process ID of the child process that performed this job's task. For deferred processes, this value is undefined until the job is launched and the child process is spawned.
The process group ID of the child process. For deferred processes, this value is undefined until the child process is spawned. It is also undefined for systems that do not implement getpgrp ("getpgrp" in perlfunc).
The time (since the epoch) at which the instance was created.
The time at which a child process was created for the job. This value will be undefined until the child process is spawned.
The time at which the child process completed and the parent
process received a SIGCHLD signal for the end of this process.
This value will be undefined until the child process is complete.
The time at which a job was reaped via a call to
Forks::Super::wait, Forks::Super::waitpid,
or Forks::Super::waitall. Will be undefined until
the job is reaped.
A string value indicating the current state of the job. Current allowable values are
DEFERREDFor jobs that are on the job queue and have not started yet.
ACTIVEFor jobs that have started in a child process and are, to the knowledge of the parent process, still running.
COMPLETEFor jobs that have completed and caused the parent process to
receive a SIGCHLD signal, but have not been reaped.
The difference between a COMPLETE job and a REAPED job
is whether the job's process identifier has been returned in
a call to Forks::Super::wait or Forks::Super::waitpid
(or implicitly returned in a call to Forks::Super::waitall).
When the process gets reaped, the global variable $?
(see "$CHILD_ERROR" in perlvar) will contain the exit status
of the process, until the next time a process is reaped.
REAPEDFor jobs that have been reaped by a call to Forks::Super::wait,
Forks::Super::waitpid, or Forks::Super::waitall.
SUSPENDEDThe job has started but it has been suspended (with a SIGSTOP
or other appropriate mechanism for your operating system) and
is not currently running. A suspended job will not consume CPU
resources but my tie up memory resources.
SUSPENDED-DEFERREDJob is in the job queue and has not started yet, and also the job has been suspended.
The exit status of a job. See CHILD_ERROR ("CHILD_ERROR" in perlvar) in
perlvar. Will be undefined until the job is complete.
One of the strings natural, cmd, or sub, indicating
whether the initial fork call returned from the child process or whether
the child process was going to run a shell command or invoke a Perl
subroutine and then exit.
The shell command to run that was supplied in the fork call.
The name of or reference to CODE to run and the subroutine
arguments that were supplied in the fork call.
The behavior of this job in the event that the system was
too "busy" to enable the job to launch. Will have one of
the string values block, fail, or queue.
If this job was deferred, the relative priority of this job.
By default undefined, but could be a CODE reference
supplied in the fork() call. If defined, it is the
code that runs when a job is ready to start to determine
whether the system is too busy or not.
If defined, contains a list of process IDs and job IDs that must complete before this job will be allowed to start.
If defined, contains a list of process IDs and job IDs that must start before this job will be allowed to start.
Indicates the earliest time (since the epoch) at which this job may start.
Indicates the latest time that this job may be allowed to run. Jobs that run past their expiration parameter will be killed.
Value supplied to the fork call about desired
operating system priority for the job.
Value supplied to the fork call about desired
CPU's for this process to prefer.
If the job has been configured for interprocess communication, these attributes correspond to the handles for passing standard input to the child process, and reading standard output and standard error from the child process, respectively.
Note that the standard read/write operations on these filehandles
can also be accomplished through the write_stdin, read_stdout,
and read_stderr methods of this class. Since these methods
can adjust their behavior based on the type of IPC channel
(file, socket, or pipe) or other idiosyncracies of your operating
system (#@$%^&*! Windows), using these methods is preferred
to using the filehandles directly.
$job = Forks::Super::Job::get($pidOrName) Looks up a Forks::Super::Job object by a process ID/job ID
or name attribute and returns the
job object. Returns undef for an unrecognized pid or
job name.
$n = Forks::Super::Job::count_active_processes() Returns the current number of active background processes. This includes only
Forks::Super module,
and not processes that may have been created outside the
Forks::Super framework, say, by an explicit call to
CORE::fork(), a call like system("./myTask.sh &"),
or a form of Perl's open function that launches an
external command.A Forks::Super::Job object recognizes the following methods.
In general, these methods should only be used from the foreground
process (the process that spawned the background job).
$job->wait( [$timeout] )$job->waitpid( $flags [,$timeout] )Convenience method to wait until or test whether the specified job has completed. See Forks::Super::waitpid.
The calls $job->wait and $job->wait() will block until a
job has completed. But $job->wait(0) will call wait with
a timeout of zero seconds, so it will be equivalent to a call of
waitpid $job, &WNOHANG.
$job->kill($signal)Convenience method to send a signal to a background job. See Forks::Super::kill.
$job->suspendWhen called on an active job, suspends the background process with
SIGSTOP or other mechanism appropriate for the operating system.
$job->resumeWhen called on a suspended job (see suspend|"$job->suspend",
above), resumes the background process with SIGCONT or other mechanism
appropriate for the operating system.
$job->is_completeIndicates whether the job is in the COMPLETE or REAPED state.
$job->is_startedIndicates whether the job has started in a background process. While return a false value while the job is still in a deferred state.
$job->is_activeIndicates whether the specified job is currently running in a background process.
$job->is_suspendedIndicates whether the specified job has started but is currently in a suspended state.
$job->toString()$job->toShortString()Outputs a string description of the important features of the job.
$job->write_stdin(@msg)Writes the specified message to the child process's standard input stream, if the child process has been configured to receive input from interprocess communication. Writing to a closed handle or writing to a process that is not configured for IPC will result in a warning.
Using this method may be preferrable to calling print with the
process's child_stdin attribute, as the write_stdin method
will take into account the type of IPC channel (file, socket, or
pipe) and may alter its behavior because of it. In a near future
release, it is hoped that the simple print to the child stdin
filehandle will do the right thing, using tied filehandles and
other Perl magic.
$line = $job->read_stdout()@lines = $job->read_stdout()$line = $job->read_stderr()@lines = $job->read_stderr()In scalar context, attempts to read a single line, and in list context, attempts to read all available lines from a child process's standard output or standard error stream.
If there is no available input, and if the Forks::Super module
detects that the background job has completed (such that no more
input will be created), then the file handle will automatically be
closed. In scalar context, these methods will return undef
if there is no input currently available on an inactive process,
and "" (empty string) if there is no input available on
an active process.
Reading from a closed handle, or calling these methods on a process that has not been configured for IPC will result in a warning.
$job->close_fh([@handle_id])Closes IPC filehandles for the specified job. Optional input
is one or more values from the set stdin, stdout, stderr,
and all to specify which filehandles to close. If no
parameters are provided, the default behavior is to close all
configured file handles.
The close_fh method may perform certain cleanup operations
that are specific to the type and settings of the specified
handle, so using this method is preferred to:
# not as good as: $job->close_fh('stdin','stderr')
close $job->{child_stdin};
close $Forks::Super::CHILD_STDERR{$job};
On most systems, open filehandles are a scarce resource and it is a very good practice to close filehandles when the jobs that created them are finished running and you are finished processing input and output on those filehandles.
$pid = $job->reuse( \%new_opts )Creates a new background process by calling Forks::Super::fork,
using all of the existing settings of the current Forks::Super::Job
object. Additional options may be provided which will override
the original settings.
Use this method to launch multiple instances of identical or similar jobs.
$job = fork { child_fh => "all",
callback => { start => sub { print "I started!" },
finish => sub { print "I finished!" } },
sub => sub {
do_something();
do_something_else();
... # do 100 other things.
},
args => [ @the_args ], timeout => 15
};
# Crikey, I'm not typing all that in again.
$job2 = $job->reuse { args => [ @new_args ], timeout => 30 };
$job->dispose()Forks::Super::Job::dispose( @jobs )Called on one or more job objects to free up any resources used by a job object. You may call this method on any job where you have finished extracting all of the information that you need from the job. Or to put it another way, you should not call this method on a job if you still wish to access any information about the job. After this method is invoked on a job, any information such as run times, status, and unread input from interprocess communication handles will be lost.
This method will
@ALL_JOBS and %ALL_JOBS variables.Any job object created by this module will be added to the list
@Forks::Super::Job::ALL_JOBS and to the lookup table
%Forks::Super::Job::ALL_JOBS. Within %ALL_JOBS, a specific
job object can be accessed by its job id (the numerical value returned
from Forks::Super::fork()), its real process id (once the
job has started), or its name attribute, if one was passed to
the Forks::Super::fork() call. This may be helpful for iterating
through all of the jobs your program has created.
my ($longest_job, $longest_time) = (-1, -1);
foreach $job (@Forks::Super::ALL_JOBS) {
if ($job->is_complete) {
$job_time = $job->{end} - $job->{start};
if ($job_time > $longest_time) {
($longest_job, $longest_time) = ($job, $job_time);
}
}
}
print STDERR "The job that took the longest was $job: ${job_time}s\n";
Jobs that have been passed to the "dispose" method are removed
from @ALL_JOBS and %ALL_JOBS.
An available feature in the Forks::Super module is to make
it more convenient to access the functionality of
Forks::Super::Job. When this feature is enabled, the
return value from a call to Forks::Super::fork() is an
overloaded Forks::Super::Job object.
$job_or_pid = fork { %options };
In a numerical context, this value looks and behaves like
a process ID (or job ID). The value can be passed to functions
like kill and waitpid that expect a process ID.
if ($job_or_pid != $another_pid) { ... }
kill 'TERM', $job_or_pid;
But you can also access the attributes and methods of the
Forks::Super::Job object.
$job_or_pid->{real_pid}
$job_or_pid->suspend
Since v0.51, the <> iteration operator has been overloaded
for the Forks::Super::Job package. It can be used to read
one line of output from a background job's standard output,
and to allow you to treat the background job object
syntactically like a readable filehandle.
my $job = fork { cmd => $command };
while (<$job>) {
print "Output from $job: $_\n";
}
Since v0.41, this feature is enabled by default.
Whether the overloading is enabled by default or not, you can override the default behavior in three ways:
FORKS_SUPER_JOB_OVERLOAD
to a true or false value$ FORKS_SUPER_JOB_OVERLOAD=0 perl a_script_that_uses_Forks_Super.pl ...
overload to the module import function
with a 0 or 1 valueuse Forks::Super overload => 1; # always enable overload feature
Forks::Super::Job::enable_overload();
Forks::Super::Job::disable_overload();
In principle you may call these methods at any time and as often as you wish.
Even when overloading is enabled, Forks::Super::fork()
still returns a simple scalar value of 0 to the child process
(when a value is returned).
Marty O'Brien, <mob@cpan.org>
Copyright (c) 2009-2011, Marty O'Brien.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.8 or, at your option, any later version of Perl 5 you may have available.
See http://dev.perl.org/licenses/ for more information.
| Forks-Super documentation | view source | Contained in the Forks-Super distribution. |