27 8 / 2011

Node Server Kill/Restart Script for OSX

There are times when it would be convenient to kill a running node server and/or restart it in an automated fashion, by name rather than by process id. It’s easy enough to kill a process in Linux, but first you have to find it. It’s simple to list all active process, filtering based on part of the process name like so, assuming a node server named “myserver”:

    ps ax | grep myserver

If myserver is indeed still running you’ll see output like this:

45727 s000  T      0:00.02 sudo node myserver
45728 s000  T      0:00.15 node myserver
45794 s000  R+     0:00.00 grep myserver

Once you know the process ID (PID) it’s a simple matter of killing it:

    sudo kill -9 45728

So just kill the process by id, and then you’re good to restart myserver. [Note: The -9 (or -KILL) switch is not always required, but was in my case. YMMV.]

Of course, each time you restart the server the process is assigned a unique PID, so if you have to kill the new process you first must find it then kill it by the new PID. In some cases this can prove inconvenient, e.g. if you want an automated clean up or restart script, say as part of a CI process.

But wait, I can hear you say, what about the awesome pkill command that can kill a process based on regex matching? I agree, that is awesome indeed — unfortunately pkill is not available on OSX. There are various alternatives, most of which seem hacky at best. You can also install an implementation of pkill (among other things) via proctools, but I really wanted to solve my problem without having to make modifications to my system first.

I finally ran across this answer on StackOverflow which gave me the basic command I needed, and from there it was a simple matter of wrapping that up into a reusable shell script.

Node Kill

It’s a very simple shell script that kills a node server by name (not PID) and optionally restarts it in a single command. For example:

    sh kill.sh -r myserver

That will terminate the ‘node myserver’ process(es) and automatically restart the server for you, simple as that.

The code is available on Github, and any suggestions for improvement are welcome.

Tags:

Permalink 10 notes