Luna/apps/shmem-test.cpp
apio b01aa72f17
All checks were successful
continuous-integration/drone/push Build is passing
libc+init+shmem-test: Add POSIX shared memory objects
2023-08-03 10:32:52 +02:00

49 lines
801 B
C++

#include <fcntl.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <unistd.h>
int main()
{
int fd = shm_open("/shared", O_CREAT | O_RDWR, 0666);
if (fd < 0)
{
perror("shm_open");
return 1;
}
ftruncate(fd, PAGE_SIZE);
void* address = mmap(nullptr, PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (address == MAP_FAILED)
{
perror("mmap");
return 1;
}
char* ptr = (char*)address;
printf("the value is %c\n", *ptr);
*ptr = 'a';
pid_t child = fork();
if (child < 0)
{
perror("fork");
return 1;
}
if (child == 0)
{
*ptr = 'e';
_exit(0);
}
waitpid(child, NULL, 0);
printf("the value is %c\n", *ptr);
return 0;
}