返回顶部

收藏

python清空linux/unix系统共享内存代码

更多
# -*- coding: utf-8 -*-
# Remove the share memory

import os
import sys
import getopt

def usage():
    print "usage: python rmsharemem.py -h -o <owner> -s size <shmid list>"
    print "  -h show help information"
    print "  -o <owner> the owner create share memory need to delete"
    print "  -s <size>  the share memory size"
    print "  <shmid list> the shmid list need to delete"

def getsharemem():
    sharemap = {}
    fp = os.popen('ipcs -m')
    lines = fp.readlines()
    for l in lines:
        if not l.startswith('0x'):
            continue

        s = l.split()
        if sharemap.has_key(s[2]):
            sharemap[s[2]].append(s)
        else:
            sharemap[s[2]] = [s]

    #print 'Share memory map:\n', sharemap
    return sharemap

if __name__ == "__main__":
    opts, args = getopt.getopt(sys.argv[1:], "o:hs:")
    # opts is the parameter with options
    # args is the parameter no ptions
    owner = None
    size = 0
    for o, p in opts:
        if o == '-h':
            usage()
            sys.exit(0)
        elif o == '-o':
            owner = p
        elif o == '-s':
            size = p

    if not owner:
        val = raw_input("Are you sure to remove all share memory?(yes/no)");
        if (val <> "yes"):
            usage()
            sys.exit(0)

    count = 0
    total = 0

    if len(args) > 0:
        for shmid in args:
            cmd = 'ipcrm -m %s' % shmid
            print 'execute command: %s' % cmd
            ret = os.system(cmd)
            total += 1
            if ret == 0:
                count += 1
                print 'remove %s shared memory success' % shmid
            else:
                print 'remove %s shared memory failed' % shmid

    else:
        shmmap = getsharemem()
        for o, l in shmmap.items():
            if owner and o <> owner:
                continue
            for p in l:
                total += 1
                if size and size <> p[4]:
                    continue

                cmd = 'ipcrm -m %s' % p[1]
                print 'execute command: %s' % cmd
                ret = os.system(cmd)

                if ret == 0:
                    count += 1
                    print 'remove %s shared memory success' % p[1]
                else:
                    print 'remove %s shared memory failed' % p[1]

    print 'total share memory number = %s' % total
    print 'remove success number = %s' % count
    sys.exit(0)

标签:python,linux,共享内存

收藏

0人收藏

支持

0

反对

0