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
| #include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#define PERM_FILE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
static int *getaddr(void) {
key_t key;
int shmid, *p;
p=NULL;
(void)close(open("shmseg", O_WRONLY | O_CREAT, 0));
if ((key = ftok ("shmseg",1)) == 1)
{
printf("Échec de ftok\n");
return(NULL);
}
if ((shmid=shmget(key,sizeof(int) ,IPC_CREAT | PERM_FILE))==1)
{
perror("Échec de ftok\n");
return(NULL);
}
if ((p=shmat(shmid,NULL,0))==((vo id *)1))
{
perror("Échec de shmat");
return(NULL);
}
return(p);
}
int main(void) {
pid_t pid;
if ((pid=fork()) == 0) {
int *p,prev=0;
if ((p=getaddr()) == NULL) {
printf("Échec de getaddr\n");
exit(EXIT_FAILURE);
}
while (*p != 99)
if (prev != *p) {
printf("Fils voit %d\n",*p);
prev = *p;
}
printf("Le fils a terminé\n");
} else {
int *p;
if ((p=getaddr()) == NULL) {
printf("Échec de getaddr\n");
exit(EXIT_FAILURE);
}
for (*p = 1; *p < 4; (*p)++)
sleep(1);
*p = 99;
}
exit(EXIT_SUCCESS);
} |
Partager