some-usable-scripts/C_Language/TP_SYS/tp_sema/producteur.c

64 lines
1.8 KiB
C
Raw Normal View History

2011-03-20 17:21:34 +01:00
#include <unistd.h>
2011-03-17 16:37:36 +01:00
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "constantes.h"
#include "types.h"
2011-03-17 16:37:36 +01:00
#include "sema.h"
int main( int argc, char **argv)
{
2011-03-17 17:31:26 +01:00
if(argc < 2) { printf("Usage %s numIPC\n", argv[0]); exit(EXIT_FAILURE); }
2011-03-20 01:03:54 +01:00
MEMP *memoireP;
int mutex_data, mutex_tpa, sem_global, continuer = 0, i=0;
2011-03-20 17:21:34 +01:00
char c;
MSG message;
key_t sem_key_data = MUTEX_DATA;
key_t sem_key_glob = MUTEX_GLOB;
key_t sem_key_tpa = MUTEX_TPA;
2011-03-20 01:03:54 +01:00
int shmid;
int shm_key = atoi(argv[1]);
2011-03-17 16:37:36 +01:00
2011-03-20 01:21:44 +01:00
shmid = shmget(shm_key, sizeof(MEMP), 0766 | IPC_CREAT);
2011-03-20 17:21:34 +01:00
if (shmid == -1) { perror("shmget"); exit(EXIT_FAILURE); }
2011-03-17 16:37:36 +01:00
2011-03-20 17:21:34 +01:00
if((memoireP = (MEMP *) shmat(shmid, 0 , 0766)) ==(void *) -1) { perror("shmat"); exit(EXIT_FAILURE); }
if((mutex_data = open_sem( sem_key_data)) == -1) { perror("open_sem"); exit(EXIT_FAILURE); }
if((mutex_tpa = open_sem( sem_key_tpa)) == -1) { perror("open_sem"); exit(EXIT_FAILURE); }
if((sem_global = open_sem( sem_key_glob)) == -1) { perror("open_sem"); exit(EXIT_FAILURE); }
2011-03-17 16:37:36 +01:00
// sem_global est un sémaphore à MAX_PROD entrants.
P(sem_global);
2011-03-20 17:21:34 +01:00
P(mutex_tpa);
for(i = 0; i < MAX_PROD && memoireP->tpa[i] != -1 ; i++);
V(mutex_tpa);
if(memoireP->tpa[i] != -1) { exit(EXIT_FAILURE); }
memoireP->tpa[i] = 0;
2011-03-20 01:21:44 +01:00
// On quitte le producteur en tappant 0 (zéro)
2011-03-20 17:21:34 +01:00
while((c = getc(stdin)) != '0')
{
2011-03-20 10:45:36 +01:00
P(mutex_data);
2011-03-20 17:21:34 +01:00
if(((memoireP->queue -1) % MAX_BUF) != (memoireP->tete % MAX_BUF) )
{
memoireP->f[memoireP->tete].c = c;
memoireP->f[memoireP->tete].idp = i;
2011-03-20 17:21:34 +01:00
memoireP->tete = memoireP->tete +1;
}
2011-03-20 10:45:36 +01:00
V(mutex_data);
2011-03-20 17:21:34 +01:00
}
// On a fini, on remet la valeur de l'indice du processus à -1 dans le tableau des producteurs
2011-03-20 17:21:34 +01:00
P(mutex_tpa);
memoireP->tpa[i] = -1;
2011-03-20 17:21:34 +01:00
V(mutex_tpa);
// On a fini, on libère l'accès à un autre producteur
V(sem_global);
2011-03-17 16:37:36 +01:00
return (EXIT_SUCCESS);
}