En utilisant une socket de type AF_INET c’est un peu différent.
#!/usr/bin/env python3importsysimportsubprocessimportsocketimportsignalimportospidFilename='/tmp/'+sys.argv[0]+'.pid'defgraceful_exit(signum,frame):print('I terminate, my PID is '+str(os.getpid())+' and I received signal '+str(signum)+'',file=sys.stderr,flush=True)sys.exit(0)try:ifsys.argv[1]=='start':sleeper=subprocess.Popen([sys.argv[0],'run'],stdin=subprocess.PIPE,shell=False)pidfile=open(pidFilename,'w')_pid=str(sleeper.pid)pidfile.write(_pid)pidfile.close()elifsys.argv[1]=='run':signal.signal(signal.SIGTERM,graceful_exit)signal.signal(signal.SIGINT,graceful_exit)server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)server.bind(('127.0.0.1',1234))server.listen(3)whileTrue:client,addr=server.accept()message=client.recv(65535).decode('UTF-8')ifmessage:print('I’m alive, my PID is '+str(os.getpid())+' and I’ve been told to say : « '+message+' »',file=sys.stderr,flush=True)elifsys.argv[1]=='stop':try:pidfile=open(pidFilename,'r')os.kill(int(pidfile.read()),signal.SIGTERM)pidfile.close()os.unlink(pidFilename)except(FileNotFoundError,ProcessLookupError):passelifsys.argv[1]=='say'andlen(sys.argv)>1:client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)client.connect(('127.0.0.1',1234))client.send(bytes(sys.argv[2],'utf8'))exceptIndexErrorase:print(str(e),file=sys.stderr)
# Pour compléter ces exemples
Posté par Marotte ⛧ . En réponse au message Communication inter-processus. Évalué à 3.
En utilisant une socket de type AF_INET c’est un peu différent.