1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| #include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/shm.h>
#include <sys/wait.h>
typedef struct
{
int nb;
const char *msg;
} shared_s;
int main (int argc, char **argv)
{
int id;
int pid;
shared_s *s = NULL;
key_t cle;
errno = 0;
cle = ftok (argv[0], 'a');
if (cle != -1)
{
errno = 0;
id = shmget (cle, sizeof (shared_s), IPC_CREAT | 0666);
if (id != -1)
{
errno = 0;
s = shmat (id, NULL, 0);
if (s != (void *)-1)
{
s->nb = 2;
s->msg = "Shared hello world";
errno = 0;
pid = fork ();
if (pid > 0)
{
/* Processus pere */
int i;
for (i = 0; i < s->nb; i++)
{
printf ("%s\n", s->msg);
}
waitpid (pid, NULL, 0);
for (i = 0; i < s->nb; i++)
{
printf ("%s\n", s->msg);
}
}
else if (pid == 0)
{
/* Processus fils */
shared_s *ss = NULL;
/*
* On laisse le temps au processus pere d'afficher le message
* d'origine.
*/
sleep (1);
ss = shmat (id, NULL, 0);
if (ss != (void *)-1)
{
ss->nb = 5;
ss->msg = "Msg modifier !";
}
else
{
perror ("shmat");
return EXIT_FAILURE;
}
}
else
{
perror ("fork");
return EXIT_FAILURE;
}
}
else
{
perror ("shmat");
return EXIT_FAILURE;
}
}
else
{
perror ("shmget");
return EXIT_FAILURE;
}
}
else
{
perror ("ftok");
return EXIT_FAILURE;
}
(void)argc;
return EXIT_SUCCESS;
} |
Partager