while (wait(100))

wait returns 0 when stop is pressed. You can make use of that info to call quit() and then return.