使用Popen打开进程并获取PID [英] Opening a process with Popen and getting the PID

查看:2036
本文介绍了使用Popen打开进程并获取PID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个漂亮的小功能:

I'm working on a nifty little function:

def startProcess(name, path):
    """
    Starts a process in the background and writes a PID file

    returns integer: pid
    """

    # Check if the process is already running
    status, pid = processStatus(name)

    if status == RUNNING:
        raise AlreadyStartedError(pid)

    # Start process
    process = subprocess.Popen(path + ' > /dev/null 2> /dev/null &', shell=True)

    # Write PID file
    pidfilename = os.path.join(PIDPATH, name + '.pid')
    pidfile = open(pidfilename, 'w')
    pidfile.write(str(process.pid))
    pidfile.close()

    return process.pid

问题在于process.pid不是正确的PID.似乎总是比正确的PID低1.例如,它说该过程开始于31729,但是ps说它在31730运行.每次我尝试将其关闭1.我猜它返回的PID是 current <的PID. /strong>进程,而不是已启动的进程,新进程将获得"next" pid,该pid高1.如果是这种情况,我不能仅仅依靠返回process.pid + 1,因为我不能保证它总是正确的.

The problem is that process.pid isn't the correct PID. It seems it's always 1 lower than the correct PID. For instance, it says the process started at 31729, but ps says it's running at 31730. Every time I've tried it's off by 1. I'm guessing the PID it returns is the PID of the current process, not the started one, and the new process gets the 'next' pid which is 1 higher. If this is the case, I can't just rely on returning process.pid + 1 since I have no guarantee that it'll always be correct.

为什么process.pid不返回新进程的PID,我如何实现所追求的行为?

Why doesn't process.pid return the PID of the new process, and how can I achieve the behaviour I'm after?

推荐答案

摘自 http://docs.python上的文档.org/library/subprocess.html :

Popen.pid子进程的进程ID.

Popen.pid The process ID of the child process.

请注意,如果将shell参数设置为True,则此过程 生成的外壳的ID.

Note that if you set the shell argument to True, this is the process ID of the spawned shell.

如果shell为false,我认为它应该表现出预期.

If shell is false, it should behave as you expect, I think.

这篇关于使用Popen打开进程并获取PID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆