简体   繁体   中英

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

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, ie 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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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