[mac/linux] Startup snippet: Automatically kill old sc processes using a default port

Just sharing a little startup file snippet for Unixy OSes. If it detects that the language port is not 57120, it runs a fuser command to find out PIDs that are on this port, then kill -9 for each one. Then it exits the sclang process so you can reboot it and get the right port.

Windows will need different commands and different pipe result processing – exercise for the reader.

var fixPorts = {
	// for unixy systems
	// windows will require a rewrite,
	// parsing the pipe result differently
	// I'm not going to do that today
	var pipe = Pipe("fuser 57120/udp", "r");
	var line;
	var pids = List.new;
	var cond = CondVar.new;
	var ok, allOK = true;
	protect {
		while {
			line = pipe.getLine.postln;
			line.notNil
		} {
			line.split($ ).do { |id|
				if(id.asInteger != 0) {
					pids.add(id)
				};
			};
		};
	} { pipe.close };
	fork {
		pids.do { |id|
			ok = false;
			"kill -9 %".format(id).unixCmd { |exit|
				if(exit == 0) {
					ok = true
				};
				cond.signalOne;
			};
			cond.waitFor(1);
			if(ok.not) {
				"Failed to stop pid %".format(id).warn;
			};
			allOK = allOK and: ok;
		};
		if(allOK) { 0.exit } { "Some processes didn't die".warn };
	};
};

if(Platform.ideName == "scqt" and: { NetAddr.langPort != 57120 }) {
	"Language port is %, networking may fail".format(NetAddr.langPort).warn;
	"Attempting to force-quit leftover processes\nIf successful, reboot the interpreter".postln;
	fixPorts.value;
};

hjh

2 Likes

This is great! Thank you!