我正在为作为传感器驱动程序的C扩展创建Python包装。 我需要用Python将Ctrl-C中断信号传递给驱动程序,以便它结束当前的采集阶段,而不启动新的采集阶段。 我发现这两个相关主题: Allowing Ctrl-C to interrupt a python C-extensionAllowing Ctrl-C to interrupt a python C-extension 但是,它们并没有回答我的问题,因为我使用的是Ctypes(见下文)。 是否有一种方法可以使用Python的线程或CType中断C扩展。我希望避免对C代码进行任何更改。 目标是停止无止境循环函数
Python代码:
import signal
import ctypes
import os
import sys
if __name__ == "__main__" :
libname = os.path.abspath(os.path.join(os.path.dirname(__file__),"clib.so"))
LIBC = ctypes.CDLL(libname)
LIBC.main.argtypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_char_p),]
args=(ctypes.c_char_p * (len(sys.argv)-1))(str.encode(sys.argv[1]))
LIBC.main(len(args),args)
signal.signal(signal.SIGINT, lambda s,f:os.kill(os.getpid(), signal.SIGTERM))
C代码:
#include <stdlib.h>
#include <stdio.h>
#incluse <string.h>
void endless_loop()
{
while(1){printf("Can't stop me ! \n");}
}
int main(int argc, char* argv[])
{
endless_loop();
return 0 ;
}
生成文件:
all: test
clean:
rm -f *.o *.so *.html
clib.so: clib.o
gcc -shared -o clib.so clib.c -fPIC
clib.o: clib.c
gcc -Wall -Werror clib.c -fPIC
test: clib.so
chmod 777 pyclib.py
python pyclib.py 2
谢天谢地
如果希望在
LIBC.main
运行时调用信号处理程序,则必须在调用LIBC.main
之前(通过signal.signal
)安装它,而不是在它返回之后但是,正如您所注意到的:它仍然不起作用。这是因为Python信号处理程序在C扩展运行时不会执行,而且由于Python主动安装了SIGINT处理程序,默认情况下Ctrl-C在这种情况下不起作用。为了使其中断程序,恢复默认信号行为:
相关问题 更多 >
编程相关推荐