shithub: mq

ref: ca32bdbe21c2092e50d6945950463a76520f499f
dir: mq/rc/pin

View raw version
#!/bin/rc
rfork e

fn create {
	mq = $1
	mkdir -p $mq
	echo replay all >$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 {
	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
}

flagfmt = 'a:attach, c:create, w:write, m:mtpt mtpt, s:srv srv'
args = 'id [command]'
eval `''{aux/getflags $*} || exec aux/usage

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

# Run and mount if not already mounted
if(! ~ `{walk -n0 -eq $mtpt >[2]/dev/null} a000000000000000.0.80){
	if(test -e /srv/$srv)
		mount -c /srv/$srv $mtpt
	if not
		mq -s $srv -m $mtpt
}

mq = $mtpt/$id
if(~ $#write 1){
	if(~ $nocmd 1)
		exec cat >>$mq/0
	if not
		exec echo $cmd >>$mq/0
}
if(~ $#create 1){
	if(test -d $mq){
		echo $mq already exists >[1=2]
		exit 'pin exists'
	}
	create $mq
}
if(~ $#attach 1)
	attach $mq