Calling a C function with a timeout

Ducobu Marc <[email protected]> Wed, 09 Mar 2011 15:44:45 +0100
Newsgroups gmane.comp.python.ctypes
Message-ID <[email protected]>
Hi.

I use ctypes in a python project where I need to call some C functions 
which can take some hours for giving response. My problem is that I want 
to kill the function (from the python code) after a certain time even if 
the function has not finish the calculation.

I tried with multithread but it doesn't stop the C function. Here is my 
code.
----------------
lib_iw = cdll.LoadLibrary("./iw.so")

iw_solve = lib_iw.solve_iw # the C function which can take some hours 
for responding
iw_solve.restype = c_void_p
iw_solve.argtypes = [c_void_p]

def iw_solve2() :
     iw_solve(None)

def iw_solve_wtimeout(time_out) : # the function which thow $iw_solve 
and kill the execution of $iw_solver after $time_out seconds (but it 
doesn't work)
     t_solve = threading.Thread(None,iw_solve2,None,(),None)
     t_solve.run()
     t = time.time()

     while(t_solve.is_alive() and ((time.time() - t) < 2)) :
         time.wait(0.3)

     if(t_solve.is_alive()) :
         print t_solve.is_alive()
         t_solve._Thread__stop()
         print "iw_solve was killed"
     else :
         print "iw_solve has respond"
----------------

I tried with alarm but it doesn't stop the c function. Here is my code.
----------------
lib_iw = cdll.LoadLibrary("./iw.so")

iw_solve = lib_iw.solve_iw # the C function which can take some hours 
for responding
iw_solve.restype = c_void_p
iw_solve.argtypes = [c_void_p]

def iw_solve_withtimeout(time_out) : # the function which thow $iw_solve 
and kill the execution of $iw_solver after $time_out seconds (but it 
doesn't work)
     signal.signal(signal.SIGALRM, handler)
     signal.alarm(time_out)
     try :
         print "debut iw_solve"
         signal.alarm(time_out)
         iw_solve(None)
     except Exception, exc:
         print exc
         return None;
----------------

Do you have some ideas for doing it using ctypes?

Thanks a lot for your help.

Marc

------------------------------------------------------------------------------
Colocation vs. Managed Hosting
A question and answer guide to determining the best fit
for your organization - today and in the future.
http://p.sf.net/sfu/internap-sfd2d