from subprocess import *
import os
from sys import stdin, stdout, stderr

def diskInfo(dev):
    devname = os.path.basename(dev)
    cmd = ["/lib/udev/scsi_id", "-g", "-x", "-s", "/block/%s"%devname, "-d", dev]
    process = Popen(cmd,shell=False,stdout=PIPE,stderr=PIPE)
    out, err = process.communicate()
    if process.returncode:
        return {}
    d = {}
    out = out[:-1]
    for line in out.split('\n'):
        attr = line.split("=")
        d[attr[0]] = attr[1]
    return d

def persistentwrite(path, data):
    fd = open(path, 'w+')
    fd.write(data)
    fd.flush()
    os.fsync(fd)
    fd.close()

def deamonize():
    if os.fork(): exit(0)
    os.umask(0) 
    os.setsid() 
    if os.fork(): exit(0)

    stdout.flush()
    stderr.flush()
    si = file('/dev/null', 'r')
    so = file('/dev/null', 'a+')
    se = file('/dev/null', 'a+', 0)
    os.dup2(si.fileno(), stdin.fileno())
    os.dup2(so.fileno(), stdout.fileno())
    os.dup2(se.fileno(), stderr.fileno())

def getPID(pidfile):
    f = open(pidfile, 'r')
    pid = int(f.read())
    f.close()
    return int(pid)

def setPID(pidfile):
    pid = str(os.getpid())
    persistentwrite(pidfile, pid)

def testPID(pid):
    try:
        os.kill(pid,0)
    except:
        return False
    return True

def isAlive(pidfile):
    if not os.path.exists(pidfile):
        return False

    if testPID(getPID(pidfile)):
        return True
    else:
        os.unlink(pidfile)
        return False
