I have just been testing a couple of programs with shared memory. One using SYSV shared memory and one using POSIX shared memory.
This first program is for SYSV shared memory:
#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <unistd.h>
int main()
{
int id = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666);
if (id == -1)
{
std::cout << "shmget failed: " << std::strerror(errno) << '\n';
return 1;
}
void* ptr = shmat(id, nullptr, 0);
if (ptr == reinterpret_cast<void*>(-1))
{
std::cout << "shmat failed: " << std::strerror(errno) << '\n';
return 1;
}
int* counter_ptr = reinterpret_cast<int*>(ptr);
*counter_ptr = 123;
pid_t pid = fork();
if (pid == -1)
{
std::cout << "fork failed: " << std::strerror(errno) << '\n';
return 1;
}
else if (pid == 0)
{
*counter_ptr = 321;
}
else
{
// Parent process
int status = 0;
waitpid(pid, &status, 0);
std::cout << "Counter: " << *counter_ptr << '\n';
}
}
The second program uses POSIX shared memory, and is very similar to the first:
#include <iostream>
#include <cstring>
#include <sys/mman.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <unistd.h>
int main()
{
void* ptr = mmap(nullptr, sizeof(int), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
if (ptr == MAP_FAILED)
{
std::cout << "mmap failed: " << std::strerror(errno) << '\n';
return 1;
}
int* counter_ptr = reinterpret_cast<int*>(ptr);
*counter_ptr = 123;
pid_t pid = fork();
if (pid == -1)
{
std::cout << "fork failed: " << std::strerror(errno) << '\n';
return 1;
}
else if (pid == 0)
{
// Child process
*counter_ptr = 321;
}
else
{
// Parent process
int status = 0;
waitpid(pid, &status, 0);
std::cout << "counter = " << *counter_ptr << '\n';
}
}