我有一个pythongui,它在启动时打开一个C子进程,在关闭时终止C子进程。你知道吗
从python发送到C和从C发送到python的信号被正确捕获。 然而,在python端接收数据时存在一些问题。你知道吗
这是我的程序:
Python代码:
fpi_c = subprocess.Popen(["./FPI_sig"],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
def handle_inform_from_c(signum, frame):
print("receved:", signum)
outstr = fpi_c.stdout.read()
print outstr
signal.signal(signal.SIGUSR1, handle_inform_from_c)
def gui_sense_and_save_fpi_2():
fpi_c.stdin.write(str(123)+"\n")
os.kill(fpi_c.pid,signal.SIGUSR1)
,其中gui_sense_and_save_fpi_2
与按钮连接。
当按下按钮时,数据和信号SIGUSR1将被发送到C子进程。你知道吗
C代码:
void signal_callback_handler2(int signum)
{
int gpid;
scanf("%d",&gpid);
printf("Caught signal %d\n",signum);
//fclose(stdout);
signal(SIGUSR1, signal_callback_handler2);
kill(getppid(),SIGUSR1);
}
int main()
{
signal(SIGUSR1, signal_callback_handler2);
while(1)
{
sleep(0.5);
}
return EXIT_SUCCESS;
}
如果我添加fclose(stdout)
,我可以在python端捕获由C打印的消息"Caught signal XXX"
。你知道吗
但是,关闭stdout
会使管道中断,我无法再发送数据。你知道吗
如果没有fclose(stdout)
行,程序将挂在outstr = fpi_c.stdout.read()
行。你知道吗
我在C中尝试过fflush(stdout)
在printf
之后,在python中尝试过fpi_c.stdin.flush()
,但仍然挂起。你知道吗
挂起时,如果我强制任务管理器关闭C进程,我可以在python端捕获消息。你知道吗
似乎python正在等待C的终止
但是,除非pythongui关闭,否则我不想关闭C进程。你知道吗
如何正确发送和接收数据?你知道吗
谢谢。你知道吗
终于找到解决办法。。。。。。你知道吗
如果Python试图从空缓冲区读取数据, 在这种情况下,它将等待来自C的输入并挂起。你知道吗
原代码中有两个问题需要解决:
在
printf
之后添加fflush(stdout)
。你知道吗否则,输出将被缓冲,除非调用
fflush(stdout)
,否则不会被实际写入。Python需要知道它应该读取多少个字符或多少行。你知道吗
不要使用
fpi_c.stdout.read()
。这将等待C输入并挂起。相反,使用fpi_c.stdout.read(1)
读取1个字符或fpi_c.stdout.readline()
读一行。像这样的。你知道吗
不要使用
fclose
输出流,而是使用fflush
刷新它,这样缓冲区中的内容就被写出来了,父进程就可以读取它了:相关问题 更多 >
编程相关推荐