Fix shutdown flag handling

This change restore reverted pull #67 then fix flag handling.
It works fine on my environment.

If possible, could you test on reviewer machine?

If still fails, I will restore brute-force code on this change.