信号量作为锁使用事例。
#!/usr/bin/perl # use strict; use IPC::Semaphore; use IPC::SysV qw(IPC_PRIVATE S_IRUSR S_IWUSR IPC_CREAT IPC_NOWAIT SEM_UNDO); our $sem = IPC::Semaphore->new(IPC_PRIVATE, 1, S_IRUSR | S_IWUSR | IPC_CREAT); $sem->setval(0,1); my $pid = fork(); die "fork failed" unless defined $pid; if ($pid > 0) { $sem->op(0,-1,SEM_UNDO); my $i = 10; while($i > 0){ print "parent process i= $i\n"; $i--; } $sem->op(0,1,SEM_UNDO); } elsif ($pid == 0){ $sem->op(0, -1, SEM_UNDO); my $i = 10; while($i > 0) { print "child process i = $i\n"; $i--; } } $sem->remove() if defined $sem;
-> # ./testsem.pl parent process i= 10 parent process i= 9 parent process i= 8 parent process i= 7 parent process i= 6 parent process i= 5 parent process i= 4 parent process i= 3 parent process i= 2 parent process i= 1 child process i = 10 child process i = 9 child process i = 8 child process i = 7 child process i = 6 child process i = 5 child process i = 4 child process i = 3 child process i = 2 child process i = 1