2020-09-04 10:27:13 +02:00

81 lines
2.4 KiB
C

///******************************************************************/
///* IUT NICE-COTE D'AZUR - Departement INFORMATIQUE - R. CHIGNOLI */
///* Module M311 Theme IPC POSIX */
///******************************************************************/
///* demo_shm.c : Demonstration d'utilisation d'un segment */
///* de memoire partagee */
///* UTILISATION : commande ( -create | -use ) */
///* Utiliser ls, etc ... pour gerer les ressources */
///******************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>
/// Type de la zone mémoire
typedef struct memoire
{
int valeur;
int date;
} Memoire;
int main(int argc, char * argv[])
{
struct memoire *zone;
int mem_fd;
if (argc != 2)
{
fprintf (stderr, "\nSyntaxe : %s ( -create | -use )\n\n", argv[0]);
exit (1);
}
mem_fd = shm_open ("demo_mem", O_CREAT |O_RDWR, 0777);
if (mem_fd == -1)
{
perror("shm_open");
exit (1);
}
if (ftruncate(mem_fd, sizeof(struct memoire)) != 0)
{
perror("ftruncate");
exit(2);
}
zone = mmap (NULL, 100, PROT_READ | PROT_WRITE, MAP_SHARED, mem_fd, 0);
if (zone == (void *) -1)
{
perror("mmap");
exit (3);
}
if ((strcmp (argv[1], "-create")!= 0) && (strcmp (argv[1], "-use")!= 0))
{
fprintf (stderr, "\nSyntaxe : %s ( -create | -use )\n\n", argv[0]);
exit (2);
}
if (strcmp (argv[1], "-create")== 0)
{
zone->valeur = 0;
zone->date =time(NULL);
printf("\nCREATE : VALEURS en memoire : valeur = %d - date = %s\n",
zone->valeur, ctime ((time_t*)&zone->date));
}
else /// -use
{
printf("\nUSE : ANCIENNES VALEURS en memoire : valeur = %d - date = %s \n",
zone->valeur, ctime ((time_t*)&zone->date));
zone->valeur++;
zone->date =time(NULL);
printf("USE : NOUVELLES VALEURS en memoire : valeur = %d - date = %s \n",
zone->valeur, ctime ((time_t*)&zone->date));
}
close(mem_fd);
return 0;
}