I have a program version A that calls execve() to execute another program version B while retaining the same PID.
This program A has a socket object and we would like the other program B to access the same socket to send some data to the established connection.
The problem is that I haven't found a way to successfully recover the serialized socket, I'm saving it to a file, opening the file again in the new program B but it is not the same object, is uninitialized and doesn't have any attributes set, I have used dill and pickle.
Is there a safe way to pass variable objects while calling exec()? Or a way to get the pointer reference of the object and pass that pointer forward?
Version A:
#!/bin/env python
import os
import dill as pickle
import socket
print "Version A"
print os.getpid()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1",80))
with open('file1.pickle', 'wb') as handle:
pickle.dump(s, handle)
os.execlp('python', 'python', 'verB.py')
Version B:
#!/bin/env python
import os,pdb,sys
import dill as pickle
import socket
print "Version B"
print os.getpid()
infile = open('file1.pickle','rb')
infile.seek(0, 0)
s = pickle.load(infile)
infile.close()
s.send("mymessage")
s.close()
Version B socket s is uninitialized, how to recover the socket?
exec? You should design your other program to be importable, that is the sanest way of accomplish this. Then you can just doimport other_program; whatever_we_need = other_program.main()socket.socket(fileno=number). Probably, if python'sexecdoes not close fds from the parent when called.execso I assumed you meant the built-inexec. Yes, as @vanza says, you can pass the fileno arg, andos.exec*shouldn't close it.