#include <iostream> #include <unistd.h> #include <sys/shm.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <stdio.h> #include <queue> int main() { int ShmID = shmget(IPC_PRIVATE, 1024, IPC_CREAT | S_IRUSR | S_IWUSR); if(ShmID == -1) { std::cout << "Cannot create shared memory" << std::endl; return -1; } pid_t ChildPid = fork(); if(ChildPid == -1) { std::cout << "Cannot fork" << std::endl; return -2; } std::queue<std::string>* str = (std::queue<std::string>*)shmat(ShmID, 0, 0); if(str == 0) { std::cout << "Cannot attach shared memory" << std::endl; return -3; } if(ChildPid == 0) { //CHild process str->push("hello"); str->push("world"); shmdt(str); return 0; } else { //parent process sleep(1); std::cout << str->front() << ' '; str->pop(); std::cout << str->front() << ' '; str->pop(); shmdt(str); shmctl(ShmID, IPC_RMID, 0); } return 0; } |
1 answer
The error is too simple - you are trying to access an object that is not created
std::queue<std::string>* str = (std::queue<std::string>*)shmat(ShmID, 0, 0); that is, str indicates memory, but what is there ... and who knows. If the usual structure can be placed like this, then C ++ classes are needed only through the constructor.
// получим указатель на память void *p = shmat(ShmID, 0, 0); // используем placement new для создания объекта по месту std::queue<std::string> * str = new(p)std::queue<std::string>(); after such a change does not fall. But you need to remember to call the destructor ( delete str; ). And apparently it needs to be called only in one of the processes. And the most important thing is not to call it when another process uses it.
You also need to carefully synchronize memory accesses, but it can be a lot of fun - std :: queue does not expect it to work with different processes.
- I changed since you said but did not help: - Արմեն Սարգսյան
- I tested it, it worked (although everything written is a hack and it’s better not to transfer classes from ++ classes) - KoVadim
- Or maybe the problem is somewhere else because it doesn’t work for me. Or can we divide the memory between the process as something good that the process was understood as a queue? - Արմեն Սարգսյան
- If there is a hundred more lines of code, it may well not work. But in general, Linux already has a queue for this out of the box (that is, from the kernel) systutorials.com/docs/linux/man/3-mq_notify - KoVadim
- There is no code as much as I sent but it does not work, but thanks - նրեն գսարգսյան
|