#!/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]$/;
$send = ($mode eq "s");

$id = msgget(0x1234, ($send ? 0 : &IPC_CREAT) | 0644);
die "Can't get message queue: $!\n" unless defined($id);
print "message queue id: $id\n";

if ($send) {
	while (<STDIN>) {
		chop;
		unless (msgsnd($id, pack("LA*", $., $_), 0)) {
			die "Can't send message: $!\n";
		}
	}
}
else {
	$SIG{'INT'} = $SIG{'QUIT'} = "leave";
	for (;;) {
		unless (msgrcv($id, $_, 512, 0, 0)) {
			die "Can't receive message: $!\n";
		}
		($type, $message) = unpack("La*", $_);
		printf "[%d] %s\n", $type, $message;
	}
}

&leave;

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