By the time system
returns, the spawned process will already exit, leaving its pid as an interesting historical link, useful for log analysis, for example.
system LIST
system PROGRAM LIST
Exactly like exec LIST
, except that fork
is executed first and the parent process expects the child process to exit & hellip;
If you want the pids of both script.pl
and newscript.pl
, fork
independently control their lifetimes. With more specific information about the problem that you can solve, we could give you more specific suggestions.
To block other instances of the program, a common method is to use the operating system. To ensure shared locking: at startup, try to lock a specific file. If successful, your program knows that this is the only one. Otherwise, another process already has a lock, so the new process ends. The following is an example.
#! /usr/bin/env perl use strict; use warnings; use Fcntl qw/ :flock /; use File::Basename; use POSIX qw/ strftime /; $0 = basename $0; my $LOCK = "$ENV{HOME}/.lock-$0"; sub logmsg { my($msg) = @_; my $t = strftime "%F %T", localtime time; warn "$0: $t - $$ - $msg\n"; } sub take_lock { open my $fh, ">", $LOCK or die "$0: open $LOCK: $!"; unless (flock $fh, LOCK_EX | LOCK_NB) { logmsg "failed to lock $LOCK; exiting."; exit 1; } $fh; } my $token = take_lock; logmsg "processing..."; sleep 2 * 60; logmsg "done.";
Note that you must leave the file descriptor returned from take_lock
open while the control is inside your critical section . The above code treats it as an opaque token. When your program exits, Perl closes the file descriptor, which automatically releases the lock. What you do not want to do is call take_lock
in the void context, because it will cancel your lock.
source share