Relationship Between Parent Child Processes

I am trying to create a Python 3 program with one or more child processes.

The parent process spawns child processes, and then continues its own business, from time to time I want to send a message to a specific child process that catches it and takes action.

In addition, the child process should not be blocked while waiting for the message, it will start its own loop that supports the connection to the server and send any returned messages to the parents.

I am currently looking at multiprocessor, threading, subprocess modules in python, but could not find any solution.

What I'm trying to achieve is to have the bulk of the program that interacts with the user, taking care of user inputs and presenting information to the user. This will be asynchronous from child parts that interact with different servers, receiving messages from the server and sending the correct messages from the user to the server. Then the child processes will send information back to the main part, where they will be pressed against the user.

My questions:

  • I am going to do it wrong.
  • Which module is best to use
    2.1 How do I configure this.
+6
source share
2 answers

See Doug Hellmann (Multiprocessing) "Process Between . " Part of his Python Module of the Week. It is quite simple to use a dictionary or list to communicate with the process.

import time from multiprocessing import Process, Manager def test_f(test_d): """ frist process to run exit this process when dictionary 'QUIT' == True """ test_d['2'] = 2 ## change to test this while not test_d["QUIT"]: print "test_f", test_d["QUIT"] test_d["ctr"] += 1 time.sleep(1.0) def test_f2(name): """ second process to run. Runs until the for loop exits """ for j in range(0, 10): print name, j time.sleep(0.5) print "second process finished" if __name__ == '__main__': ##--- create a dictionary via Manager manager = Manager() test_d = manager.dict() test_d["ctr"] = 0 test_d["QUIT"] = False ##--- start first process and send dictionary p = Process(target=test_f, args=(test_d,)) p.start() ##--- start second process p2 = Process(target=test_f2, args=('P2',)) p2.start() ##--- sleep 3 seconds and then change dictionary ## to exit first process time.sleep(3.0) print "\n terminate first process" test_d["QUIT"] = True print "test_d changed" print "data from first process", test_d time.sleep(5.0) p.terminate() p2.terminate() 
+3
source

It sounds like you are familiar with multiprocessing, just not python.

os.pipe will provide you channels for connecting parent and child. And semaphores can be used to coordinate / signal between parent and child processes. You might want to consider queues for messaging.

+2
source

Source: https://habr.com/ru/post/888834/


All Articles