1

I have an issue where I am trying to have a thread in Python sleep in the background for a specified time. This needs to be done in the program though, not at the command-line level, as there is data being passed out of the Python program into PHP.

import os
from threading import Thread

class getPID(Thread):
    def run(self):
        print os.getpid()

class waitToKill(Thread):
    def run(self):
        time.sleep(25) #This is the sleep that needs to be done in the background
        os.system('pkill process')

getPID().start()
waitToKill().start()

The concept is that PHP will repeatedly start the Python program, then take the PID and kill the process before it hits the pkill statement. When someone leaves the page, the Python program will have been started, but not killed, thusly reaching the pkikll statement and closing the process started by entering the page.

This is about as simple as I can conceive making a Dead Man's Switch in PHP/Python, but it requires background sleep, as the PHP exec() function does not run things in the background well while still receiving std output. (i.e. exec(dms.py &) will hang for 25s before returning the PID and displaying the rest of the page)

What is the best way to accomplish this? Should it be at the time.sleep() level or the thread level? Or can the PHP exec() function be modified to send output while still running in the background?

Thanks for any help you can provide!

4

1 回答 1

0

完全没有必要为此任务使用线程——在所有线程退出之前,进程不会被认为已完成,因此让主线程提前完成没有任何好处。

您必须执行以下操作之一:

  • 以无需等待进程完成的方式从 PHP 执行脚本(请参阅:php 执行后台进程
  • 分叉python进程或以其他方式启动一个新的python进程,以便原始进程可以快速退出
于 2012-08-06T18:30:57.767 回答