how to terminate postgresql 8.3 sessions?

user972276 picture user972276 · Mar 21, 2013 · Viewed 7.9k times · Source

I am trying to terminate a session (a specific session or all sessions, doesnt matter) in postgresql 8.3 and am having trouble doing that. I know in newer versions (8.4 and later) there is a pg_terminate_backend command that will do the trick but this is not available in postgresql 8.3. If I use pg_stat_activity, I can see all the sessions that are active but have no way of terminating them.

The solution does not have to necessarily be sql commands but I would like it to be independent of the OS that is being used (i.e. no DOS/UNIX commands).

Stopping and starting the postgres service in windows services works perfectly but this is an OS specific approach. Using 'pg_ctl restart -D DATA_DIR' does not stop the service however. Actually using pg_ctl to try and restart the service at the time I am trying to do it causes some weird behavior. If there is a way I can somehow use pg_ctl to force shutdown the process like I assume windows does, then I can probably use that.

Anyways, I am looking for a way to terminate one or all sessions in postgresql 8.3 that is not platform specific. Any help would be great!

Answer

Ilion picture Ilion · Mar 21, 2013

You can use pg_cancel_backend():

select pg_cancel_backend(55555);

You can use this with pg_stat_activity. For example:

select pg_cancel_backend(procpid)
from pg_stat_activity where current_query='<IDLE>';

If that doesn't work you can try this:

pg_ctl kill -TERM pid

That should be OS independent. I'm not sure if there's any real difference in behaviour.

Other than that you could try stopping and starting the server, but you indicated odd behaviour from that. (What kind?)

Finally, for an OS specific option, on linux you can of course try using the kill command. kill -15 (SIGTERM) is safe; that's basically what pg_terminate_backend uses: kill -15 <pid>. kill -9 is moderately unsafe and you should use it only as a last resort.