2

Can somebody help me understand why is my code executed twice?

import multiprocessing
from time import sleep
import os, signal

def neverEnding():
    while True:
        print ' Looping ... '
        sleep(3)


p = multiprocessing.Process(target=neverEnding)
p.start()

sleep(10)
print p.is_alive()

print p.pid
p.terminate()
print p.is_alive()
print 'terminated?'

os.kill(int(p.pid), signal.SIGTERM)
print 'Now?'
sleep(3)
print p.is_alive()

This is the output I'm getting.

 Looping ... 
 Looping ... 
 Looping ... 
 Looping ... 
True
8999
True
terminated?
Now?
False
 Looping ... 
 Looping ... 
 Looping ... 
 Looping ... 
True
9000
True
terminated?
Now?
False

I'm getting 'terminated?', 'Now?' etc... printed twice.
Can somebody explain why does this happen?

Will the other processes running in the background cause this? (I had run the same script using subprocess before)

I'm using Ubuntu.

Jithin Pavithran
  • 1,250
  • 2
  • 16
  • 41
  • are you running this script in windows? then see http://stackoverflow.com/questions/14175348/why-does-pythons-multiprocessing-module-import-main-when-starting-a-new-pro and http://stackoverflow.com/questions/20222534/python-multiprocessing-on-windows-if-name-main – ymonad Jul 21 '16 at 01:58
  • actually running your code in Linux prints 'terminated?' only once – ymonad Jul 21 '16 at 02:03
  • I'm using Ubuntu, updated in question – Jithin Pavithran Jul 21 '16 at 02:11
  • I'm getting 'terminated?' twice. It's direct copy paste of my terminal output. – Jithin Pavithran Jul 21 '16 at 02:12
  • 1
    maybe [this](http://stackoverflow.com/questions/9857006/trying-to-understand-multiprocessing-with-main-in-python) helps. – GAVD Jul 21 '16 at 09:36

1 Answers1

0

Which python version do you use? I am using 2.6.9 on linux, the same code as yours but get the different result:

 *Looping ...
 Looping ...
 Looping ...
 Looping ...
True
6634
True
terminated?
Now?
False*

The problem of why after "p.terminate()" the process is still alive is due to the parent process can not get the sub-process state that fast. If I add a sleep(0.1) in between:

p.terminate()
sleep(0.1)
print p.is_alive()

I get the following result:

 Looping ...
 Looping ...
 Looping ...
 Looping ...
True
7046
False
terminated?
Traceback (most recent call last):
  File "./test_m.py", line 24, in <module>
    os.kill(int(p.pid), signal.SIGTERM)
OSError: [Errno 3] No such process

The subprocess is terminated, so os.kill(int(p.pid), signal.SIGTERM) get an error!

Anssen
  • 31
  • 3