[英]Sharing Variable between C and Python
我正在使用命名管道FIFO在C(生成數字的循環是C)和python(偵聽C生成的數字並讀取並處理它們)之間進行通信。 除了C中每個生成的數字以外,代碼都運行良好,我需要關閉fifo才能在Python中看到它,否則,直到調用close命令,它才會在python中顯示。 我不知道打開和關閉FIFO是否能夠以python代碼正確讀取它們不是一個好主意。 我需要注意,C代碼每50毫秒生成一次數字。 這就是為什么我懷疑打開和關閉是否是個好主意的原因。 這是我在C和Python中編寫的代碼:
C作為服務器:
while (1){
t=time_in_ms();
if (t-t0>=50){
t0=t;
flag=1;
}
else{
flag=0;
}
if (flag==1){
flag=0;
printf("%lld %lld\n",count,t);
count+=1;
fprintf(f,"%lld\r",t);
fflush(f);
fclose(f);
f=fopen("fifo","w");
}
}
並以Python作為客戶端代碼:
with open(FIFO) as fifo:
print("FIFO opened")
while True:
data = fifo.read()
if len(data) == 0:
count=count+1
else:
count=0
if count>2000:
print("Writer closed")
break
print data
x=x+1
這是一個小的工作示例
Python方面:
with open('./test_out.fifo', 'r') as fo:
message = fo.readline()
print(message)
在“服務器” C端
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
int fifo_fd;
fifo_fd = open("./test_out.fifo", O_WRONLY);
dprintf(fifo_fd, "testing123\n");
while(1)
{
sleep(1);
}
return 0;
}
C程序末尾的無窮循環只是為了證明我們不需要在python程序中讀取數據之前就關閉文件
我還應該說我已經有一段時間沒有做C代碼了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.