473,583 Members | 3,061 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Example Code : Shared Memory with Mutex (pywin32 and ctypes)

Hello,
Here is some sample code with pywin32 build 203 and ctypes 0.9.6.

Best regards,
/Srijit

File: SharedMemCreate _Mutex_win32all .py

# This application should be used with SharedMemAccess _Mutex_ctypes.p y
or SharedMemAccess _Mutex_win32all .py
#~ a) Creates a shared memory
#~ b) Creates or Opens a mutex
#~ c) Reads the contents (null terminated string) of shared memory
#~ d) Acquires a mutex and then writes a null terminated string to the
shared memory
#~ e) Sleeps upto 2 seconds. Sleep time is generated by a random number
#~ f) Repeats steps (c), (d) and (e) indefintely

import mmap, random, time
import win32event, pywintypes, win32api

def main():
SHMEMSIZE = 256

ERROR_ALREADY_E XISTS = 183

szName = "MyFileMappingO bject"
szMsg1 = "Message from first process using win32all and mmap - "
szMutex = "MyMutexObj ect"

shmem = mmap.mmap(0, SHMEMSIZE, szName, mmap.ACCESS_WRI TE)

try:
hMutex = win32event.Crea teMutex(None, pywintypes.FALS E,
szMutex)
if (win32api.GetLa stError() == ERROR_ALREADY_E XISTS):
print"Opened existing mutex object", szMutex
else:
print "Created new mutex"

i=0
random.seed()
while 1:
szMsg1 = szMsg1 + hex(i) + "\0"
if (len(szMsg1) > SHMEMSIZE):
print "Current size of string message is", len(szMsg1),
"and greater than", SHMEMSIZE
break
shmem_read = shmem.read(SHME MSIZE)
shmem_read = shmem_read.rstr ip(chr(0))
shmem_read = shmem_read.rstr ip(" ")
print "RECEIVED from SECOND Process: ", shmem_read
shmem.seek(0)
wait_result = win32event.Wait ForSingleObject (hMutex, 1000)
if (wait_result == win32event.WAIT _OBJECT_0):
shmem.write(szM sg1)
while (shmem.tell() != SHMEMSIZE):
shmem.write_byt e(" ")
shmem.seek(0)
print "WROTE in FIRST process: ", szMsg1
win32event.Rele aseMutex(hMutex )
elif(wait_resul t == win32event.WAIT _TIMEOUT):
print "COULD NOT ACQUIRE MUTEX. TIMEOUT OCCURED"
elif (wait_result == win32event.WAIT _ABONDONED):
print "WAIT ABANDONED"
i = i + 1
szMsg1 = "Message from first process using win32all and
mmap - "
time.sleep(rand om.random()*2)

except pywintypes.erro r, (errno, object, strerror):
print "Error in", object, ":", strerror

if __name__ == "__main__":
main()
File: SharedMemCreate _Mutex_ctypes.p y

# This application should be used with SharedMemAccess _Mutex_ctypes.p y
or SharedMemAccess _Mutex_win32all .py
#~ a) Creates a shared memory
#~ b) Creates or Opens a mutex
#~ c) Reads the contents (null terminated string) of shared memory
#~ d) Acquires a mutex and then writes a null terminated string to the
shared memory
#~ e) Sleeps upto 2 seconds. Sleep time is generated by a random number
#~ f) Repeats steps (c), (d) and (e) indefintely
# There are two options to implement this code - Option A or Option B.
If Option B(A) is chosen then
# Option A(B) should be commented.
import random, time
from ctypes import *

def main():
try:
SHMEMSIZE = 256

TRUE = 1
FALSE = 0
ERROR_ALREADY_E XISTS = 183
FILE_MAP_ALL_AC CESS = 0xF001F
WAIT_OBJECT_0 = 0
WAIT_TIMEOUT = 0x102
WAIT_ABANDONED = 0x80
PAGE_READWRITE = 0x04
INVALID_HANDLE_ VALUE = 0xFFFFFFFF

szName = "MyFileMappingO bject"
szMsg1 = "Message from first process using ctypes - "
szMutex = "MyMutexObj ect"

hMutex = windll.kernel32 .CreateMutexA(N one, FALSE, szMutex)
if (hMutex == 0):
raise WinError()
elif (windll.kernel3 2.GetLastError( ) == ERROR_ALREADY_E XISTS):
print"Opened existing mutex object", szMutex
else:
print "Created new mutex"

hMap = windll.kernel32 .CreateFileMapp ingA(INVALID_HA NDLE_VALUE,
None, PAGE_READWRITE, 0, SHMEMSIZE, szName)
if (hMap == 0):
print "Could not open file mapping object"
raise WinError()

MapViewOfFile = windll.kernel32 .MapViewOfFile
MapViewOfFile.r estype = POINTER(c_char) # Option A
pBuf = MapViewOfFile(h Map, FILE_MAP_ALL_AC CESS, 0, 0, 0)
if (pBuf == 0):
raise WinError()

i=0
random.seed()
while 1:
szMsg1 = szMsg1 + hex(i) + "\0"
pBuf_str = cast(pBuf, c_char_p) # Option A
if (len(szMsg1) > SHMEMSIZE):
print "Current size of string message is", len(szMsg1),
"and greater than", SHMEMSIZE
break
print "RECEIVED from SECOND Process: ", pBuf_str.value #
Option A
#~ print "RECEIVED from SECOND Process: ", string_at(pBuf)
# Option B
wait_result = windll.kernel32 .WaitForSingleO bject(hMutex,
1000)
if (wait_result == WAIT_OBJECT_0):
memset(pBuf, ord(" "), SHMEMSIZE)
cdll.msvcrt.str cpy(pBuf_str, szMsg1) # Option A
#~ cdll.msvcrt.str cpy(pBuf, szMsg1) # Option B
print "WROTE in FIRST process: ", szMsg1
release_mutex = windll.kernel32 .ReleaseMutex(h Mutex)
if (release_mutex == 0):
print "CANNOT RELEASE ACQUIRED MUTEX"
elif(wait_resul t == WAIT_TIMEOUT):
print "COULD NOT ACQUIRE MUTEX. TIMEOUT OCCURED"
elif (wait_result == WAIT_ABONDONED) :
print "WAIT ABANDONED"
i = i + 1
szMsg1 = "Message from first process using ctypes - "
time.sleep(rand om.random()*2)

windll.kernel32 .UnmapViewOfFil e(pBuf)
windll.kernel32 .CloseHandle(hM ap)
return
except WindowsError, (strerror):
print strerror
if (pBuf != 0):
windll.kernel32 .UnmapViewOfFil e(pBuf)
if (hMap != 0):
windll.kernel32 .CloseHandle(hM ap)
return

if __name__ == "__main__":
main()
File : SharedMemAccess _Mutex_win32all .py

# This application should be used with SharedMemCreate _Mutex_ctypes.p y
or SharedMemCreate _Mutex_win32all .py
#~ a) Opens an existing shared memory
#~ b) Opens an existing mutex
#~ c) Reads the contents (null terminated string) of shared memory
#~ d) Acquires a mutex and then writes a null terminated string to the
shared memory
#~ e) Sleeps upto 2 seconds. Sleep time is generated by a random number
#~ f) Repeats steps (c), (d) and (e) indefintely

import mmap, random, time
import win32event, pywintypes

def main():
SHMEMSIZE = 256

STANDARD_RIGHTS _REQUIRED = 0xF0000
SYNCHRONIZE = 0x100000
MUTANT_QUERY_ST ATE = 0x1

MUTEX_ALL_ACCES S = STANDARD_RIGHTS _REQUIRED | SYNCHRONIZE |
MUTANT_QUERY_ST ATE

szName = "MyFileMappingO bject"
szMsg1 = "Message from second process using win32all and mmap - "
szMutex = "MyMutexObj ect"

shmem = mmap.mmap(0, SHMEMSIZE, szName, mmap.ACCESS_WRI TE)
try:
hMutex = win32event.Open Mutex(MUTEX_ALL _ACCESS,
pywintypes.FALS E, szMutex)
print"Opened existing mutex object", szMutex
i = 0;
random.seed()
while 1:
szMsg1 = szMsg1 + hex(i) + "\0"
if (len(szMsg1) > SHMEMSIZE):
print "Current size of string message is", len(szMsg1),
"and greater than", SHMEMSIZE
break
shmem_read = shmem.read(SHME MSIZE)
shmem_read = shmem_read.rstr ip(chr(0))
shmem_read = shmem_read.rstr ip(" ")
print "RECEIVED from FIRST Process: ", shmem_read
shmem.seek(0)
wait_result = win32event.Wait ForSingleObject (hMutex, 1000)
if (wait_result == win32event.WAIT _OBJECT_0):
shmem.write(szM sg1)
while (shmem.tell() != SHMEMSIZE):
shmem.write_byt e(" ")
shmem.seek(0)
print "WROTE in SECOND process: ", szMsg1
win32event.Rele aseMutex(hMutex )
elif(wait_resul t == win32event.WAIT _TIMEOUT):
print "COULD NOT ACQUIRE MUTEX. TIMEOUT OCCURED"
elif (wait_result == win32event.WAIT _ABONDONED):
print "WAIT ABANDONED"
i = i + 1
szMsg1 = "Message from second process using win32all and
mmap - "
time.sleep(rand om.random()*2)
except pywintypes.erro r, (errno, object, strerror):
print "Error in", object, ":", strerror

shmem.close()
return
if __name__ == "__main__":
main()
File: SharedMemAccess _Mutex_ctypes.p y

# This application should be used with SharedMemCreate _Mutex_ctypes.p y
or SharedMemCreate _Mutex_win32all .py
#~ a) Opens an existing shared memory
#~ b) Opens an existing mutex
#~ c) Reads the contents (null terminated string) of shared memory
#~ d) Acquires a mutex and then writes a null terminated string to the
shared memory
#~ e) Sleeps upto 2 seconds. Sleep time is generated by a random number
#~ f) Repeats steps (c), (d) and (e) indefintely
# There are two options to implement this code - Option A or Option B.
If Option B(A) is chosen then
# Option A(B) should be commented.
import random, time
from ctypes import *

def main():

SHMEMSIZE = 256

FILE_MAP_ALL_AC CESS = 0xF001F
STANDARD_RIGHTS _REQUIRED = 0xF0000
SYNCHRONIZE = 0x100000
MUTANT_QUERY_ST ATE = 0x1
MUTEX_ALL_ACCES S = STANDARD_RIGHTS _REQUIRED | SYNCHRONIZE |
MUTANT_QUERY_ST ATE
WAIT_OBJECT_0 = 0
WAIT_TIMEOUT = 0x102
WAIT_ABANDONED = 0x80
TRUE = 1
FALSE = 0

szName = "MyFileMappingO bject"
szMsg1 = "Message from second process using ctypes - "
szMutex = "MyMutexObj ect"

hMap = 0
pBuf = 0
hMutex = 0

try:
hMap = windll.kernel32 .OpenFileMappin gA(FILE_MAP_ALL _ACCESS,
FALSE, szName)
if (hMap == 0):
raise WinError()

MapViewOfFile = windll.kernel32 .MapViewOfFile
MapViewOfFile.r estype = POINTER(c_char) # Option A
pBuf = MapViewOfFile(h Map, FILE_MAP_ALL_AC CESS, 0, 0, 0)
if (pBuf == 0):
raise WinError()

hMutex = windll.kernel32 .OpenMutexA(MUT EX_ALL_ACCESS, FALSE,
szMutex)
if (hMutex == 0):
raise WinError()
else:
print"Opened existing mutex object", szMutex

i=0
random.seed()
while 1:
szMsg1 = szMsg1 + hex(i) + "\0"
pBuf_str = cast(pBuf, c_char_p) # Option A
if (len(szMsg1) > SHMEMSIZE):
print "Current size of string message is", len(szMsg1),
"and greater than", SHMEMSIZE
break
print "RECEIVED from FIRST Process: ", pBuf_str.value #
Option A
#~ print "RECEIVED from FIRST Process: ", string_at(pBuf) #
Option B
wait_result = windll.kernel32 .WaitForSingleO bject(hMutex,
1000)
if (wait_result == WAIT_OBJECT_0):
memset(pBuf, ord(" "), SHMEMSIZE)
cdll.msvcrt.str cpy(pBuf_str, szMsg1) # Option A
#~ cdll.msvcrt.str cpy(pBuf, szMsg1) # Option B
print "WROTE in SECOND process: ", szMsg1
release_mutex = windll.kernel32 .ReleaseMutex(h Mutex)
if (release_mutex == 0):
print "CANNOT RELEASE ACQUIRED MUTEX"
elif(wait_resul t == WAIT_TIMEOUT):
print "COULD NOT ACQUIRE MUTEX. TIMEOUT OCCURED"
elif (wait_result == WAIT_ABONDONED) :
print "WAIT ABANDONED"
i = i + 1
szMsg1 = "Message from second process using ctypes - "
time.sleep(rand om.random()*2)

windll.kernel32 .UnmapViewOfFil e(pBuf)
windll.kernel32 .CloseHandle(hM ap)
return
except WindowsError, (strerror):
print strerror
if (pBuf != 0):
windll.kernel32 .UnmapViewOfFil e(pBuf)
if (hMap != 0):
windll.kernel32 .CloseHandle(hM ap)
return

if __name__ == "__main__":
main()

Jul 18 '05 #1
0 4384

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
1881
by: Philip Rittenhouse | last post by:
I was just wondering if there are any plans to support the CreateTypeLib2 API either instead of, or in addition to, the CreateTypeLib API. I am currently using pythoncom to generate type libraries, but I ran into an issue supporting optional parameters. After a lot of digging I discovered that the old CreateTypeLib API doesn't support...
5
2799
by: Egor Bolonev | last post by:
import os print os.listdir("\\\\delta\\public") outputs and import os print os.listdir("\\\\delta")
4
5666
by: paritosh mahana | last post by:
Hi all, How can I call python code from my C# code. One thing is to make an ..exe file of the python program and then try to call it from my C# code. But I don't like that idea. Is there any other way to do this. Like making a .dll file from the python code and somehow call it from C# program.But I couldn't find anything on this topic on the...
1
7603
by: Srijit Kumar Bhadra | last post by:
Hello, Here are code snippets to create and access shared memory in Python with and without ctypes module. With regards, Srijit Filename : SharedMemCreate.py import msvcrt, mmap
6
547
by: Grandpa Pete | last post by:
How can I share resources across all users of a web service for read/write access. *Situation* *one*: I want to have an in memory counter that all users of the webservice could access. Call it g_count. Then I create a web method called Update_g_count.
6
1311
by: MobileBoy36 | last post by:
Hi All, I want to make a LogFile class that is thread safe. I use a Mutex for it. But the behavior of the class is not that normal. In a c# guide I read you can achieve it by simply using Mutex.Waitone and Mutex.ReleaseMutex. Is that right? What 's wrong with my sub Writelog then? Best regards, Mobileboy
19
11309
by: citronelu | last post by:
Is it possible to execute a binary string stored within a python script as executable code ? The script is run under Windows, and the binary code (a full executable file) is stored in a variable in the script. I know I can use os.system() or os.popen() to run an external file, but these functions take as argument a string evaluated as...
2
1667
by: gaurav kashyap | last post by:
Dear all, I have a server program that listens to a particular port and a number of client programs that connect to the server. Now i want to put some data in form of python list in main memory on server.Hence whenver a client program is run it connects to the server and access the data in main memory.Here the server calls a module that...
1
3499
by: Dog Walker | last post by:
I need to call a function in a shared object with this signature: init_dialog(FILE *input, FILE *output) The FILE*'s are to stdin and stdout. The call from python is libdialog.init_dialog( x, y) I need to define x and y so that they will have the structure of sys.stdin and sys.stdout; the called function (init_dialog) is using a (std?)...
0
8168
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8316
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
8187
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6573
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5691
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5367
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3812
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3837
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1149
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.