Hanging A Process With Select

In my last article I talked about how to stop a Unix process. There’s another technique that you can use if you control the source code for the program you’re trying to pause.

The prototype for select(2) is like this:

int select(int nfds, fd_set *readfds, fd_set *writefds,
           fd_set *exceptfds, struct timeval *timeout);

If you set nfds to zero and supply NULL for all three fd sets then select() will sleep for the amount of time in timeout. If you set timeout to NULL then the call to select() will block forever, like so:

// C: put the process in blocking-wait forever
select(0, NULL, NULL, NULL, NULL);

You can use this technique in other languages too. For instance, in Python you get:

# Python: put the process in blocking-wait forever
import select
select.select([], [], [])

I prefer this to using SIGSTOP when I actually control the source code for the program, since it makes it easier to control exactly where the program pauses. I’ve frequently found this trick useful when writing programs that create temporary files. By forcing the process to pause itself while the temporary file exists and before it’s deleted, it’s easier to poke around in another terminal to look at the state of things to figure out what’s going on.

One thing to be aware of with this technique is that only the thread that’s calling select(2) will be blocked. If you want to stop all threads I would recommend using a debugger like GDB, or sending SIGSTOP to the process group leader.