0

I am currently trying to pass a std::queue<std::pair<KInstruction*, int>> variable from child to parent process.
However, the data that parent process does not correct. All of the std::pair that in the queue that parent received looks like NULL, [some random int], but it is supposed to be some address, 1 or -1 or 0.
Here is what I do.

extern::queue<std::pair<KInstruction*, int>> queue;
std::queue<std::pair<KInstruction*, int>> tmp;
if (pid == 0) {
    ...
       compute queue
    ...
    tmp = queue

    close(fd[P1_READ]);
    close(fd[P1_WRITE]);

    // tmp is the queue variable
    if (write(fd[P2_WRITE], &tmp, sizeof(tmp)) < 0) {
        perror("Child: Failed to write response value");
        exit(EXIT_FAILURE);
    }
    close(fd[P2_READ]);
    close(fd[P2_WRITE]);
} else {
    wait(NULL);

    close(fd[P2_READ]);
    close(fd[P2_WRITE]);

    read(fd[P1_READ], &tmp, sizeof(tmp));
    close(fd[P1_READ]);
    close(fd[P1_WRITE]);
}

The queue's size that parent receive is correct. But all the data is wrong.

What I actually trying to do is to let parent process use the queue that child process compute. If anyone has better solution is appreciated.

Jiakuan
  • 65
  • 1
  • 7
  • We'll have to assume that `fd` is an integer array of size 4, that P{1,2}_{READ,WRITE} are all defined correctly, and that your calls to `pipe` were correct and did not fail. – William Pursell Dec 29 '17 at 03:13
  • Why are you closing P1_WRITE *after* you read from it? The read will not see EOF until the other side is closed. – William Pursell Dec 29 '17 at 03:14
  • @WilliamPursell I have tried to pass a int val to parent process, it success. – Jiakuan Dec 29 '17 at 03:16
  • @WilliamPursell I am following this post [link](https://stackoverflow.com/questions/12864265/using-pipe-to-pass-integer-values-between-parent-and-child). – Jiakuan Dec 29 '17 at 03:18
  • You can't just write a non-POD type like that. You are transmitting some internal data - likely a couple of pointers - not the actual data that the queue contains. Think about it: you are transmitting `sizeof(tmp)` bytes, which is a compile-time constant - but the number of elements added to the queue at runtime can be arbitrarily large. Read about [serialization](https://en.wikipedia.org/wiki/Serialization) – Igor Tandetnik Dec 29 '17 at 04:06

0 Answers0