shithub: mq

ref: 3418e498f2a4c0e763bbe9d2191b646c6bde5d4d
dir: /rc/pin/

View raw version
#!/bin/rc
rfork en

flagfmt = 'n:noattach, w:write, m:mtpt mtpt'
args = 'name [command]'
eval `''{aux/getflags $*} || exec aux/usage

srv = pin-$user
name = $1
if(~ $#name 0)
	exec aux/usage
cmd = $*(2-)
if(~ $#cmd 0){
	nocmd = 1
	cmd = (rc -i)
}
if(~ $#mtpt 0)
	mtpt = /n/pin

# Check if already mounted
if(! ~ `{walk -n0 -eq $mtpt} a000000000000000.0.80){
	if(test -e /srv/$srv)
		mount -c /srv/$srv $mtpt
	if not
		mq -s $srv -m $mtpt
}

mq = $mtpt/$name
if(~ $#write 1){
	if(~ $nocmd 1)
		exec cat >>$mq/0
	if not
		exec echo $cmd >>$mq/0
}

fn detach {
	echo creating $mq >[1=2]

	mq = $1
	mkdir -p $mq
	echo replay on >$mq/ctl
	touch $mq/^(0 1 2 note)
	$cmd <$mq/0 >>$mq/1 >>[2]$mq/2 &
	cat $mq/note >/proc/$apid/notepg &
}

fn term {
	for(p in $killem)
		echo -n kill >/proc/$p/note
}

fn input {
	while(){
	syscall -o read 0 buf 8192 >/env/buf >[2]/dev/null \
	|| {term; exit 'read error'}
	switch(`{cat /env/buf}){
	case q
		term; exit
	case *
		walk -es /env/buf | awk '
			{for(i = 0; i < $1; i++) printf "%c", 8}' >/dev/cons
		cat /env/buf
	}}
}

fn attach {
	echo attaching $mq >[1=2]

	rfork e
	mq = $1
	fn sigint {
		echo -n interrupt >>$mq/note
		status = interrupted
	}
	fn sighup sigkill { term }
	mq-cat $mq 0 1 2 &
	killem = ($killem $apid)
	input </fd/0 >>$mq/0 &
	wait $apid
	while(~ $status interrupted)
		wait $apid
}

if(! test -d $mq)
	detach $mq
if(~ $#noattach 0)
	attach $mq