Hi,

I'm currently experimenting with QSharedMemory and QProcess in PyQt. So I wrote a small application to launch a process. From this process I create a shared memory segment and write data to it. The application reads the data back when the process writes on the output. Unfortunately I get this error when the application attempts to attach to the shared memory segment: QSharedMemory::handle: doesn't exist.

Is it possible to do this sort of things ? Or maybe I should use a different approach to achieve this ?

Thanks for the help!
-mab

My application code:
Qt Code:
  1. from PyQt4 import QtGui, QtCore
  2. import sys
  3. import pickle
  4.  
  5. class Widget(QtGui.QWidget):
  6. def __init__(self):
  7. super(Widget,self).__init__()
  8.  
  9. # create process
  10. self.p = QtCore.QProcess(self)
  11.  
  12. # Connect to process output
  13. self.p.readyReadStandardOutput.connect( self.on_process_output )
  14.  
  15. self.key = 'share_mem_key'
  16. self.shmem = QtCore.QSharedMemory( key )
  17.  
  18. self.p.start( 'python.exe test_process.py "%s"' % self.key )
  19.  
  20. def on_process_output(self):
  21. self.shmem = QtCore.QSharedMemory( self.key )
  22. if not self.shmem.isAttached() and not self.shmem.attach():
  23. # Error when trying to attach to the shared memory segment
  24. print 'ERROR %s ' % self.shmem.errorString()
  25.  
  26. self.shmem.lock()
  27. try:
  28. print pickle.loads(self.shmem.data().asstring())
  29. finally:
  30. self.shmem.unlock()
  31.  
  32. # application loop
  33. app = QtGui.QApplication(sys.argv)
  34. widget = Widget()
  35.  
  36. widget.show()
  37. app.exec_()
To copy to clipboard, switch view to plain text mode 

The external process code:
Qt Code:
  1. from PyQt4 import QtCore
  2. import ctypes
  3. import ctypes.util
  4. import pickle
  5. import sys
  6.  
  7. CLIB = ctypes.cdll.LoadLibrary(ctypes.util.find_library('c'))
  8.  
  9. def main(argv):
  10. key = argv[1]
  11.  
  12. # write to shared memory
  13. data = range(50000)
  14. data_bytes = pickle.dumps( data, pickle.HIGHEST_PROTOCOL)
  15. data_len = len(data_bytes)
  16.  
  17. shmem = QtCore.QSharedMemory(key)
  18. if not shmem.create(data_len):
  19. sys.stderr.write( 'ERROR: shared memory creation' )
  20. sys.stderr.flush()
  21. return
  22.  
  23. if not shmem.isAttached() and not shmem.attach():
  24. sys.stderr.write( 'ERROR: shared memory access' )
  25. sys.stderr.flush()
  26. return
  27.  
  28. shmem.lock()
  29. try:
  30. CLIB.memcpy(int(shmem.data()), data_bytes, data_len)
  31. finally:
  32. shmem.unlock()
  33.  
  34. sys.stdout.write( 'done' )
  35. sys.stdout.flush()
  36.  
  37. if __name__ == '__main__':
  38. main(sys.argv)
To copy to clipboard, switch view to plain text mode