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

61 lines
1.6 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;
2011-03-20 17:21:34 +01:00
int mutex_data, mutex_tpa, mutex_glob, continuer = 0, i=0;
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((mutex_glob = open_sem( sem_key_glob)) == -1) { perror("open_sem"); exit(EXIT_FAILURE); }
2011-03-17 16:37:36 +01:00
2011-03-20 17:21:34 +01:00
P(mutex_glob);
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
2011-03-20 17:21:34 +01:00
memoireP->tpa[i] = getpid();
2011-03-20 10:45:36 +01:00
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 = getpid();
memoireP->tete = memoireP->tete +1;
}
2011-03-20 10:45:36 +01:00
V(mutex_data);
2011-03-20 17:21:34 +01:00
}
P(mutex_tpa);
V(mutex_tpa);
V(mutex_glob);
2011-03-17 16:37:36 +01:00
return (EXIT_SUCCESS);
}