runaway process… on a mac

wresting with the command line, and some cool cli programs I learned on the way

I want desperately to know how to detach a process from one terminal, and re-attach it to another, without using screen from the get-go. The more I read about it, the more I figure that the answer (you can’t) probably has more to do with my lack of understanding of how processes and terminals work. I read a great post here that introduced me to disown -h (careful) and nohup, some really great bash builtins. I thought, ok, lets try it. This is where I got stuck.

I tried

while true; do sleep 10; done &
disown -h %1
exit

The disown builtin handles a problem with background processes: From the bash man page (and also the above blog)

The shell exits by default upon receipt of a SIGHUP

therefore killing your process you ‘thought’ you put in the background, and then logged out to go home for the night. Disown tells the jobspec not to accept a SIGHUP, and the -h switch tells it to remain in the jobs table. I thought, cool, maybe if it stays in the the jobs table, I could also transfer it to another jobs table of another tty. (no, you can’t…)
but now I had a process on my hands that wasn’t attached to a terminal, and would just run forever unless I rebooted.

The while loop itself didn’t have a process ID, which is interesting, and because of the nature of while, the sleep commands PID kept changing, so a normal ps aux | grep slee[p] | awk '{print $2}' | xargs kill -9 wasn’t working. (This post is loosing topic fast, but the slee[p] in the above command was a cool trick I learned so that I didn’t need a grep -v grep in there).

I *did* find that I could use ps to figure out the ppid (parent process ID) and just kill -9 that, but I was also interested in knowing for sure that it wasn’t in charge of doing something else important. A little digging around, and I came across the UNIX utility pstree which of course didn’t come on my mac, but I quickly figured out that it could be installed with

sudo port install pstree

Yesterday, I had done a similar thing with the UNIX command watch, which also nicely installed using port
And, for those who don’t know, the UNIX command watch is a great poller utility, that will display the first screen’s worth of output of any command, and update it on a regular basis.

I used ps | grep to find the ppid of the sleep process, then ran this command:

watch "pstree $PPID"

This was way cool, as every ten seconds, I watched as the PID of sleep (the child process of this bash process I had just found) changed.

Take away:

sudo port install watch
sudo port install pstree
Share:
  • del.icio.us
  • Reddit
  • Technorati
  • Twitter
  • Facebook
  • Google Bookmarks
  • HackerNews
  • PDF
  • RSS
This entry was posted in programming. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.