• # Pour compléter ces exemples

    Posté par . En réponse au message Communication inter-processus. Évalué à 3.

    En utilisant une socket de type AF_INET c’est un peu différent.

    #!/usr/bin/env python3
    import sys
    import subprocess
    import socket
    import signal
    import os
    pidFilename = '/tmp/'+sys.argv[0]+'.pid'
    def graceful_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:
     if sys.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()
     elif sys.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)
     while True:
     client, addr = server.accept()
     message = client.recv(65535).decode('UTF-8')
     if message:
     print('I’m alive, my PID is '+str(os.getpid())+' and I’ve been told to say : « '+message+' »', file=sys.stderr, flush=True)
     elif sys.argv[1] == 'stop': 
     try:
     pidfile = open(pidFilename,'r')
     os.kill(int(pidfile.read()), signal.SIGTERM)
     pidfile.close()
     os.unlink(pidFilename)
     except (FileNotFoundError, ProcessLookupError):
     pass
     elif sys.argv[1] == 'say' and len(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'))
    except IndexError as e:
     print(str(e), file=sys.stderr)