summaryrefslogtreecommitdiff
path: root/eg/sysvipc/ipcshm
blob: ecc1ba4366c57b3b093380b2bfeff01a0bbbd64f (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
47
48
49
50
#!/usr/bin/perl
eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
	if $running_under_some_shell;

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

$| = 1;

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

$SIZE = 32;
$id = shmget(0x1234, $SIZE, ($send ? 0 : &IPC_CREAT) | 0644);
die "Can't get shared memory: $!\n" unless defined($id);
print "shared memory id: $id\n";

if ($send) {
	while (<STDIN>) {
		chop;
		unless (shmwrite($id, pack("La*", length($_), $_), 0, $SIZE)) {
			die "Can't write to shared memory: $!\n";
		}
	}
}
else {
	$SIG{'INT'} = $SIG{'QUIT'} = "leave";
	for (;;) {
		$_ = <STDIN>;
		unless (shmread($id, $_, 0, $SIZE)) {
			die "Can't read shared memory: $!\n";
		}
		$len = unpack("L", $_);
		$message = substr($_, length(pack("L",0)), $len);
		printf "[%d] %s\n", $len, $message;
	}
}

&leave;

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