summaryrefslogtreecommitdiff
path: root/eg/sysvipc/ipcsem
blob: e0dc551bc5f765f34d25313170c021d26a8390ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/usr/bin/perl
eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
	if $running_under_some_shell;

require 'sys/ipc.ph';
require 'sys/msg.ph';

$| = 1;

$mode = shift;
die "usage: ipcmsg {r|s}\n" unless $mode =~ /^[rs]$/;
$signal = ($mode eq "s");

$id = semget(0x1234, 1, ($signal ? 0 : &IPC_CREAT) | 0644);
die "Can't get semaphore: $!\n" unless defined($id);
print "semaphore id: $id\n";

if ($signal) {
	while (<STDIN>) {
		print "Signalling\n";
		unless (semop($id, pack("sss", 0, 1, 0))) {
			die "Can't signal semaphore: $!\n";
		}
	}
}
else {
	$SIG{'INT'} = $SIG{'QUIT'} = "leave";
	for (;;) {
		unless (semop($id, pack("sss", 0, -1, 0))) {
			die "Can't wait for semaphore: $!\n";
		}
		print "Unblocked\n";
	}
}

&leave;

sub leave {
	if (!$signal) {
		$x = semctl($id, 0, &IPC_RMID, 0);
		if (!defined($x) || $x < 0) {
			die "Can't remove semaphore: $!\n";
		}
	}
	exit;
}