Luna/apps/shmem-test.cpp

51 lines
855 B
C++
Raw Normal View History

#include <fcntl.h>
2023-08-02 20:19:47 +00:00
#include <stdio.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <unistd.h>
int main()
{
2023-08-12 19:38:25 +00:00
pledge("stdio rpath wpath cpath proc", nullptr);
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);
2023-08-02 20:19:47 +00:00
if (address == MAP_FAILED)
{
perror("mmap");
return 1;
}
char* ptr = (char*)address;
printf("the value is %c\n", *ptr);
*ptr = 'a';
2023-08-02 20:19:47 +00:00
pid_t child = fork();
if (child < 0)
{
perror("fork");
return 1;
}
if (child == 0)
{
*ptr = 'e';
2023-08-02 20:19:47 +00:00
_exit(0);
}
waitpid(child, NULL, 0);
printf("the value is %c\n", *ptr);
2023-08-02 20:19:47 +00:00
return 0;
}