triple fault
triple fault

Reputation: 14138

Different processes, same PID | Python

I'm trying to spawn few processes using the multiprocessing module. However when I call os.getpid() each process returns the same PID as the main calling process.

Why? I'm using Python 2.7 on Ubuntu 14.04.

class Listener(multiprocessing.Process):
    def __init__(self, _ttl):
        super(Listener, self).__init__()
        self.ttl = _ttl
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.bind(('localhost', 0))

    def get_pid(self):
        return os.getpid()  

    def get_name(self):
        return self.socket.getsockname()

    def run(self):
        self.socket.listen(1)
        time.sleep(self.ttl)

    def listen(self):
        self.start()

class TestEx1(unittest.TestCase):
    def test_address_to_pid(self):
        listener1 = Listener(12)
        listener2 = Listener(12)
        listener3 = Listener(12)
        listener1.listen()
        listener2.listen()
        listener3.listen()
        address1 = str(str(listener1.get_name()[0])) + ":" + str(listener1.get_name()[1])
        address2 = str(str(listener2.get_name()[0])) + ":" + str(listener2.get_name()[1])
        address3 = str(str(listener3.get_name()[0])) + ":" + str(listener3.get_name()[1])

        print listener1.get_pid()
        print ex1.address_to_pid(address1)

        print listener2.get_pid()
        print ex1.address_to_pid(address2)

        print listener3.get_pid()
        print ex1.address_to_pid(address3)


        assert(str(ex1.address_to_pid(address1)) == str(listener1.get_pid()))
        assert(str(ex1.address_to_pid(address2)) == str(listener2.get_pid()))
        assert(str(ex1.address_to_pid(address3)) == str(listener3.get_pid()))

        listener2.join()
        listener2.join()
        listener3.join()

Upvotes: 3

Views: 1782

Answers (1)

suztomo
suztomo

Reputation: 5202

It is because os.getpid() is called from the original process that runs the test.

The Listener instances are Python objects accessible in the original processes. Because these objects are instances of multipricessing.Process they may help the original process to spawn new processes. In original process of test, however, TestEx1 class is calling os.getpid() via these objects (in the original process). That's why they return same pid.

In order to get pid of the Listener processes, call listener1.pid attribute after the process starts. Documentation explains

pid

Return the process ID. Before the process is spawned, this will be None.

Upvotes: 1

Related Questions