Wednesday, October 12, 2016

Interactively Waiting On A Command -- Beer:30 Waits for No Command

As my work-day on Thursday was approaching the end, I was facing a predicament.  I had kicked off a long-running command that was uncompressing some 5000+ files earlier in the day, not knowing how long it would take.  It appeared that it would complete in the next couple hours and while I wanted to kick off some tests afterwards, I really didn't want to stick around until it completed.

Often, when this happens I would guess-timate the remaining time and issue a 'sleep' followed by the subsequent command.  Trouble is, what if I over-guessed?  Wasting valuable execution time.  Worst, what if I under-guessed?  A kicked off subsequent command could likely fail and the overnight opportunity would be wasted.  Had I anticipated this situation, I'd simply have created a script with each step and the timing would work itself out.  Unfortunately, I hadn't done so and stopping and restarting the command sequence seemed undesirable.

The 'kill' command seems to be the answer.

The steps include:
1) issuing the 'ps -aef' command to identify the process id of the command you wish to wait for
2) write an interactive script, or script file if you wish, that loops waiting for that process to complete
3) run the subsequent commands

Start by running some long command;


$ ./longCommand


Open an independent terminal and identify the process id of the 'long command';

$ ps -aef | grep longCommand
user  8186  7903  0 21:34 pts/2    00:00:00 /bin/bash ./longCommand
user  8207  8195  0 21:35 pts/17   00:00:00 grep --color=auto longCommand


Then, wait for this process to complete;

$ while kill -0 8186; do sleep 5; done; echo "done"


Followed by running whatever subsequent command(s) you wish.

The following video demonstrates this for your amusement.

Hope this helps.




No comments:

Post a Comment