繁体   English   中英

从一个 Linux 应用程序到另一个在树莓派上的 C++ 中的最简单的 IPC

[英]Simplest IPC from one Linux app to another in C++ on raspberry pi

我需要从 RPi 上运行的一个 C++ 应用程序到另一个应用程序的最简单、最可靠的 IPC 方法。

我要做的就是从一个应用程序向另一个应用程序发送 40 个字符的字符串消息

第一个应用程序在启动时作为服务运行,另一个应用程序稍后启动,经常退出并重新启动以进行调试

第二个应用程序的频繁调试是导致我迄今为止尝试过的 IPC 出现问题的原因

我尝试了大约 3 种不同的方法,这里是它们失败的地方:

  1. File FIFO,问题是一个程序挂起,而另一个程序正在写入文件

  2. 共享内存:无法在一个线程上初始化并从另一个线程读取。 在调试时频繁退出导致 GDB 崩溃, the following GDB command is taking too long to complete -stack-list-frames --thread 1

  3. 带有 localhost 的 UDP 套接字 - 与上述相同的问题,加上不正确的退出阻塞了套接字,迫使我重新启动设备

  4. 非阻塞管道 - 在接收过程中没有收到任何消息

我还能尝试什么? 我不想获得 DBus 库,对于这个应用程序来说似乎太复杂了。

任何简单的服务器和客户端代码或指向它的链接都会有所帮助

这是我的非阻塞管道代码,它对我不起作用,我假设它是因为我没有引用从一个应用程序到另一个应用程序的管道

代码来自这里: https : //www.geeksforgeeks.org/non-blocking-io-with-pipes-in-c/

char* msg1 = "hello"; 
char* msg2 = "bye !!"; 
int p[2], i;

bool InitClient()
{   
    // error checking for pipe 
    if(pipe(p) < 0) 
        exit(1); 

    // error checking for fcntl 
    if(fcntl(p[0], F_SETFL, O_NONBLOCK) < 0) 
        exit(2); 

    //Read
    int nread; 
    char buf[MSGSIZE]; 

    // write link 
    close(p[1]); 

    while (1) { 

        // read call if return -1 then pipe is 
        // empty because of fcntl 
        nread = read(p[0], buf, MSGSIZE); 
        switch (nread) { 
        case -1: 

            // case -1 means pipe is empty and errono 
            // set EAGAIN 
            if(errno == EAGAIN) { 
                printf("(pipe empty)\n"); 
                sleep(1); 
                break; 
            } 

        default: 

            // text read 
            // by default return no. of bytes 
            // which read call read at that time 
            printf("MSG = % s\n", buf); 
        } 
    } 

    return true;
}   

bool InitServer()
{      
    // error checking for pipe 
    if(pipe(p) < 0) 
        exit(1); 

    // error checking for fcntl 
    if(fcntl(p[0], F_SETFL, O_NONBLOCK) < 0) 
        exit(2); 


    //Write
    // read link 
    close(p[0]); 

    // write 3 times "hello" in 3 second interval 
    for(i = 0 ; i < 3000000000 ; i++) { 
        write(p[0], msg1, MSGSIZE); 
        sleep(3); 
    } 

    // write "bye" one times 
    write(p[0], msg2, MSGSIZE); 

    return true;
}       

请考虑 ZeroMQ

https://zeromq.org/

它是轻量级的,并且具有所有主要编程语言的包装器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM