RatDon
RatDon

Reputation: 3543

Python end parent process from thread

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.

Upvotes: 1

Views: 172

Answers (1)

RatDon
RatDon

Reputation: 3543

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.)

Upvotes: 1

Related Questions