Search code examples
pythoncmultithreadingctypesexit

Prevent exit(1) from exiting Python when executing C-function from Python


I'm executing a C function from python using ctypes. Under certain conditions, the C function I'm calling exits using exit(1), and I am not in a position where I can change this behaviour. I wish for my Python program to keep running even after this exit signal. I've attempted using threading to solve the issue; however, my program still exits on the exit signal.

my_lib.c

#include <stdio.h>
#include <stdlib.h>
void c_func(int i)
{
    if(i == 3)
        exit(1);
    printf("%d", i);
}

my_program.py

from ctypes import *
import threading
lib = CDLL("my_lib.so")
for i in range(8):
    thread = threading.Thread(target=lib.c_func, args=(i))
    thread.start()

Desired output on running my_program.py:
0124567

Actual output:
012


Solution

  • A multiprocessing solution works:

    import ctypes as ct
    import multiprocessing as mp
    
    dll = ct.CDLL('./test')
    dll.c_func.argtypes = ct.c_int,
    dll.c_func.restype = None
    
    def func(i):
        dll.c_func(i)
    
    if __name__ == '__main__':
        ps = [mp.Process(target=func, args=(i,)) for i in range(8)]
        for p in ps:
            p.start()
        for p in ps:
            p.join()
    

    Output from running in parallel so output varies. Put the join inside the first for to run serially:

    0125647