Old stuff/ecole_etude_fac_de_pau/licence_3/systeme-d-exploitation/tp4/main.c~
(Deskargatu)
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <malloc.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <sys/sem.h>
union semun {
int val; /* valeur pour SETVAL */
struct semid_ds *buf; /* buffer pour IPC_STAT, IPC_SET */
unsigned short *array; /* table pour GETALL, SETALL */
struct seminfo *__buf; /* buffer pour IPC_INFO */
};
void fonction(int n)
{
char* test;
key_t cle= ftok("./prout",0);
int id;
id = shmget(cle,0,0);
if (id == -1)
{
perror("shmget");
exit(-1);
}
// printf("Id = %d\n",id);
test = (char*)shmat(id,0, 0);
printf("On lit %s\n",test);
shmdt(test);
exit(-1);
}
int main(int argc, char** argv)
{
int semid;
union semun arg;
struct sembuf buf;
unsigned short int table[1];
table[0]=1;
arg.array = table;
pid_t pid;
char* test=NULL;
key_t cle= ftok("./prout",0);
int id;
const char source[] = "salut";
/*semaphore*/
pid= fork();
if (pid == -1) {
perror("fork");
exit(-1);
}
else if(pid == 0)
{
struct sigaction action;
action.sa_handler = fonction;
sigemptyset(&action.sa_mask);
if(sigaction(SIGUSR1,&action,NULL) == -1)
{
perror("Erreur sigaction SIGALRM\n");
exit(-1);
}
while(1) { sleep(1); }
}
else
{
semid = semget(IPC_PRIVATE, 1, IPC_CREAT|IPC_EXCL|0777);
printf("Semaphore : %d\n",semid);
arg.val = 1;
if (semctl(semid, 0, SETVAL,arg) == -1)
{
perror("semctl");
exit(-1);
}
/* Synchro */
buf.sem_num = 1;
buf.sem_flg = SEM_UNDO;
buf.sem_op = -1;
printf("Passage avant %d %d %d\n",buf.sem_num,buf.sem_flg,buf.sem_op);
if (semop(semid, &buf, 1) == -1)
{
perror("semop");
exit(-1);
}
printf("Passage apres %d %d %d\n",buf.sem_num,buf.sem_flg,buf.sem_op);
id = shmget(cle,100*sizeof(char),IPC_CREAT|IPC_EXCL|0777);
if (id == -1)
{
perror("shmget");
exit(-1);
}
// printf("Id = %d\n",id);
test = (char*)shmat(id,0, 0);
if ((int)test == -1) { perror("error shmat"); exit(-1); }
// printf("Adresse %d\n",test);
memcpy(test,source,sizeof(source)+1);
printf("On ecrit : %s\n",test);
kill(pid,SIGUSR1);
wait();
shmdt(test);
shmctl(id, IPC_RMID, NULL);
/* Liberation */
buf.sem_op = 1;
semop(semid, &buf, 1);
printf("Semaphore apres %d\n",arg.val);
/*destruction du sémaphore*/
semctl(semid, 0, IPC_RMID, 0);
}
return 1;
}