Home > Enterprise >  SOCKET PYTHON serve code dont working with SSH closed
SOCKET PYTHON serve code dont working with SSH closed

Time:07-16

I have a socket serv (a gateway) in python to recive packges from a car tracker. When I put the code to run (python3 filename.py &) in the AWS machine (using a CMD on windows) and I keep with the SSH open, the code run perfectaly, but the code print some prints on my SSH (until I know, with the "&" in the end off the comand nothing should be print in my SSH). The problem is: when i close the SSH and open again/other, I do a "ps -axf python3" and the process keep running (ok, that it should be happen) but the code dont "work" more.

This is a part of my code

class ThreadedServer(object):     

    
def __init__(self, host, port):
    self.host = host     
    self.port = port     
    self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)     
    self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  
    self.sock.bind((self.host, self.port))  

    
def listen(self):
    global connecteds
    connecteds = {}   
    compareTimeConnecteds()   
    self.sock.listen()

    while True:
        client, address = self.sock.accept() 
        client.settimeout(60*5)               
        threading.Thread(target = self.listenToClient,args = (client,address)).start()       

    
def listenToClient(self, client, address):
    bufferSize = 4096 
    while True: 
      .
      .
      .
      code to process the package from the car tracker
      .
      .
      .

if __name__ == "__main__":
  ThreadedServer('',port).listen()

As I said, after if I close the SSH, the code keep running, but it don't enter in the While(TRUE) on the listenToClient, and with the SSH open (start the code and never close) it enter....

I dont know why this happen, I think what the problem is maybe not in the code....

Someone have a ideia why this happen, I am a new in the programming world

2022/07/15 - i needed do a tmux new on my shh to so send execute my python file

CodePudding user response:

I don't think running python programs as daemons using & works as intended. How to make a Python script run like a service or daemon in Linux

Instead, once you ssh, try opening a tmux window to start the socket server.

tmux new
python3 filename.py

This will have the running of that program attached to the tmux window now created. To leave the window press "ctrl b d".

Now you should be able to leave the tunnel and the program will persist.

To go back to the tmux session, run

tmux a

this can also be done with other tools https://unix.stackexchange.com/questions/521200/exit-shell-with-running-process-in-foreground

  • Related