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
| #include <sys/types.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <strings.h>
#define TAILLE 1024
struct sembuf up = {0,1,0};
struct sembuf down = {0,-1,0};
void ecrire_tableau(int *compteur, char *tableau) {
char message[64], *msg=message;
int my_sem = semget(IPC_PRIVATE,1,0600|IPC_CREAT);
snprintf(message, 64, "Je suis le processus %d!\n", getpid());
semop(my_sem,&down,1);
while ((*compteur<TAILLE)&&(*msg)) {
semop(my_sem,&up,1);
tableau[*compteur] = *msg;
msg++;
usleep(100000);
semop(my_sem,&down,1);
(*compteur)++;
}
semctl(my_sem,0,IPC_RMID);
}
int main() {
int id, *compteur;
char *tableau;
id = shmget((key_t)1234,TAILLE+sizeof(int),0600|IPC_CREAT);
if (id<0) {perror("Error shmget"); exit(1); }
compteur = (int*) shmat(id,0,0);
if (compteur==NULL) { perror("Error shmat"); exit(1); }
tableau = (char *)(compteur + 1);
ecrire_tableau(compteur, tableau);
printf("%s\n", tableau);
if (shmdt(compteur)<0) { perror("Error shmdt"); exit(1);}
return 0;
} |
Partager