AAE-CNAS-Labs/Task-8/task_8_1.c

69 lines
1.4 KiB
C
Raw Normal View History

2021-04-21 17:32:03 +02:00
// man ftruncate
// pass any message between two processes using shared memory
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
2021-04-29 19:36:08 +02:00
#include <time.h>
2021-04-21 17:32:03 +02:00
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, char *argv[]) {
2021-04-29 19:36:08 +02:00
srandom(time(NULL));
2021-04-21 17:32:03 +02:00
const char *memory_name = "/memory";
char message[] = "Hello there";
int fd = shm_open(memory_name, O_CREAT | O_RDWR, 0777);
if (fd < 0) {
fprintf(stderr, "shm_open: ");
exit(EXIT_FAILURE);
}
printf("Shred memory file descriptor: %d\n", fd);
if (ftruncate(fd, sizeof(message)) < 0) {
fprintf(stderr, "ftruncate: \n");
exit(EXIT_FAILURE);
}
pid_t pid;
pid = fork();
if (pid == -1) {
perror("fork: ");
exit(EXIT_FAILURE);
}
if (pid == 0) {
char *addr = mmap(NULL, sizeof(message), PROT_READ, MAP_SHARED, fd, 0);
printf("Value: %s\n", addr);
if (addr == MAP_FAILED) {
fprintf(stderr, "mmap: ");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
char *addr = mmap(NULL, sizeof(message), PROT_WRITE, MAP_SHARED, fd, 0);
if (addr == MAP_FAILED) {
fprintf(stderr, "mmap: ");
exit(EXIT_FAILURE);
}
strcpy(addr, message);
shm_unlink(memory_name);
int status;
wait(&status);
munmap(addr, sizeof(message));
return 0;
}