Old stuff/ecole_etude_fac_de_pau/licence_3/systeme-d-exploitation/tp4/exo1.c
(Deskargatu)
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
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)
{
pid_t pid;
char* test=NULL;
key_t cle= ftok("./prout",0);
int id;
const char source[] = "salut";
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
{
/* Synchro */
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);
}
return 1;
}