Writing a Shared Queue for a multi-process c/c++ program

2.2k views Asked by At

Can anyone give me a good example of a multi-process shared queue (FIFO) in C/C++?

Please note, I am not looking for a thread(pthread) based implementation. Although I welcome suggestions for multi-threaded as well..

Basically looking for something that can work with fork and exec, since I have an already written application using fork/exec.

** IPC Pipes are also something I'm not looking for, as they die if either of the processes sender/receiver dies *** I would like something which is not transient, i.e. the queue can wait for the other process to become active?

I've found solutions for threads in Intel TBB's and boost threading libraries. But I'm looking for something more in the shared memory domain.

1

There are 1 answers

1
Patricio Sard On

For IPC (inter process communication) I've used pipes on a Unix system, here's an example.

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>

#define BUFF_SIZE 50
#define READ 0
#define WRITE 1

int main() {
    char write_msg[BUFF_SIZE] = "Hi, this is child proces!!!";
    char read_msg[BUFF_SIZE];

    int fd[2];

    pid_t pid;

    pipe(fd);

    pid = fork();

    if (pid == 0) {
        close(fd[READ]);
        write(fd[WRITE], write_msg, strlen(write_msg) + 1);
        close(fd[WRITE]);
    }
    else {
        close(fd[WRITE]);
        read(fd[READ], read_msg, BUFF_SIZE);
        printf("The message is: %s", read_msg);
        close(fd[READ]);
    }

    return 0;
} 

This won't work on Windows, but if I were in your place I would look for a way to use pipes (or another IPC mechanisms).