1

My aim is to create a new process which will take a number as input from user in a loop and display the square of it. If the user doesn't enter a number for 10 seconds, the process should end (not the main process). I'm using threading.Timer with multiprocessing.

Tried Code

from threading import Timer
import multiprocessing as mp
import time

def foo(stdin):
    while True:
        t = Timer(10, exit, ())
        t.start()
        print 'Enter a No. in 10 Secs: ',
        num = int(stdin.readline())
        t.cancel()
        print 'Square of', num, 'is', num*num

if __name__ == '__main__':
    newstdin = os.fdopen(os.dup(sys.stdin.fileno()))
    proc1 = mp.Process(target = foo, args = (newstdin, ))
    proc1.start()
    proc1.join()
    print "Exit"
    newstdin.close()

But it's not working. Instead of exit I tried with sys.exit, Taken proc1 as global and tried proc1.terminate, But still no solution.

RatDon
  • 3,403
  • 8
  • 43
  • 85
  • 1
    Using `threading.Timer` with `multiprocessing.Process` might not be a happy couple, try not mix threads and processes. http://stackoverflow.com/questions/25297627/why-no-timer-class-in-pythons-multiprocessing-module – d6bels Feb 27 '15 at 09:46
  • @d6bels I've read it at some places. But there is no other way to achieve what I want. – RatDon Feb 27 '15 at 09:48
  • 1
    Well as long as you only use the timer in the subprocess I don't think this is so bad ;-) – d6bels Feb 27 '15 at 09:51
  • 1
    @d6bels Initially I was planning with `multiprocessing` only and no use of `threading`. For the above task, I tried `scheduler` with `sched` a lot. But not seemed to work for me. So `Timer`. :-) – RatDon Feb 27 '15 at 10:11
  • It looks like [XY problem](http://meta.stackexchange.com/a/66378/137096): if you want *"raw_input with timeout"* then you could [use `select()` or `msvcrt.kbhit()` depending on your system](http://stackoverflow.com/q/1335507/4279). – jfs Feb 27 '15 at 14:09

1 Answers1

1

Replaced exit with os._exit and it's working as expected.

t = Timer(10, os._exit, [0])

os._exit takes exactly 1 argument, hence we have to mention 0 in a list. (In threading.Timer to pass arguments to the function, the arguments should be in a list.)

RatDon
  • 3,403
  • 8
  • 43
  • 85