Friday, January 16, 2009

mmap_test.py

Another program out of boredem. For my CSE451 class, I was reading about IPC, and SHM and mmap() were discussed in the text. Thus, I looked into Python's support, and it looks like mmap() is included. The program here is essentially a "deranged cat," which uses two processes for no reason:

mmap_test.py

#!/usr/bin/python
from mmap import mmap
from os import fork, waitpid, WEXITSTATUS
from sys import exit, stdin

map = mmap(-1, 1024)
map.seek(0)
map.write_byte(chr(0))

pid = fork()
if pid == 0:
while True:
map.seek(0)
b = map.read_byte()
while b == chr(0):
map.seek(0)
b = map.read_byte()
if b == chr(3):
break
else:
print map.readline().rstrip()
map.seek(0)
map.write_byte(chr(0))
exit(0)._exit()
else:
while True:
st = stdin.readline(1022)
if st == '':
map.seek(0)
map.write_byte(chr(3))
break
else:
map.seek(1)
map.write(st)
map.seek(0)
map.write_byte(chr(1))

map.seek(0)
while map.read_byte() == chr(1):
map.seek(0)

id, status = waitpid(pid, 0)
map.close()
print 'Child exited with', WEXITSTATUS(status)
Post a Comment