linuxprocessipcinter-process-communicat

Proper implementation of an inter process communication (IPC)


Is the following a proper implementation of an inter-process communication?

#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;
}

It seems to be working but I'm wondering if there could be a race condition leading to hanging. One constraint is that both processes need to be started independently and in any order.


Solution

  • Some stress tests showed no problem so the implementation seems OK if somebody wants to reuse the code.