【问题标题】:Proper implementation of an inter process communication (IPC)正确实现进程间通信 (IPC)
【发布时间】:2015-01-29 12:31:17
【问题描述】:

以下是进程间通信的正确实现吗?

#include <stdio.h>
#include <fcntl.h>
#include <sys/poll.h>

int main(int argc, char** argv) {
    if (argc > 1) {
//Sending side
        struct stat buffer;
        if (stat("/tmp/PROCAtoPROCB", &buffer) != 0)
            mkfifo("/tmp/PROCAtoPROCB", (mode_t)0600);

        int fdFIFO = open("/tmp/PROCAtoPROCB", O_WRONLY | O_NONBLOCK);
        if (fdFIFO > 0) {
            write(fdFIFO, (void *)argv[1], sizeof(argv[1]));
            close(fdFIFO);
        }
    } else {
//Receiving side
        int fdFIFO = -1;
        struct stat buffer;
        if (stat("/tmp/PROCAtoPROCB", &buffer) != 0)
            mkfifo("/tmp/PROCAtoPROCB", (mode_t)0600);

        while (1) {
            struct pollfd pollfds[1];
            if (fdFIFO == -1)
                fdFIFO = open("/tmp/PROCAtoPROCB", O_RDONLY | O_NONBLOCK);
            pollfds[0].fd = fdFIFO;
            pollfds[0].events = POLLIN;
            poll(pollfds, 1, -1);
            if (pollfds[0].revents & POLLIN) {
                char buf[1024];
                read(fdFIFO, &buf, 1024);
                close(fdFIFO);
                fdFIFO = -1;
                printf("Other process says %s\n", buf);
            }
            printf("End of loop\n");
        }
    }
    return 0;
}

它似乎正在工作,但我想知道是否存在导致挂起的竞争条件。一个限制是,两个进程都需要独立启动,并且可以按任意顺序启动。

【问题讨论】:

    标签: linux process ipc inter-process-communicat


    【解决方案1】:

    一些压力测试表明没有问题,所以如果有人想重用代码,实现似乎没问题。

    【讨论】:

      猜你喜欢
      • 2011-08-25
      • 2011-03-22
      • 2011-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-11
      • 2015-02-25
      • 2014-09-21
      相关资源
      最近更新 更多