Added Task-8-1

This commit is contained in:
Sergiusz Warga 2021-04-21 17:32:03 +02:00
parent 3f5797a903
commit 653f699dab

65
Task-8/task_8_1.c Normal file
View File

@ -0,0 +1,65 @@
// 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>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, char *argv[]) {
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;
}