代码之家  ›  专栏  ›  技术社区  ›  user2684657

在C和Python之间共享变量

  •  0
  • user2684657  · 技术社区  · 7 年前

    代码运行良好,除了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
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   David Bern    7 年前

    下面是一个小的工作示例

    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代码了。