PHP Code:
#include <sys/ipc.h>
#include <sys/shm.h>
#include <st***.h>
#include <sys/types.h>
#include <stdlib.h>
#include <errno.h>
/***
* _ _
* (_) (_)
* __ ____ _ _ _____ ___ ___ ___ ___ _ __ ___
* \ \/ / _` | |/ _ \ \ / / |/ _ \ / __/ _ \| '_ ` _ \
* > < (_| | | (_) \ V /| | (_) | (_| (_) | | | | | |
* /_/\_\__, |_|\___/ \_/ |_|\___(_)___\___/|_| |_| |_|
* __/ |
* |___/
*
*
* Shared Memory and Critical Sections between parent and child - fork()
*
*
*/
#define SHMSZ 100
#define KEY 9999
int main ( void ) {
int shmid, status, shmdet, shmcontrol,err;
void * shmatt;
int * new_area;
/////////////creazione memoria condivisa
shmid = shmget ( KEY, SHMSZ, IPC_CREAT | IPC_EXCL | 660);
if (shmid == -1) { fprintf (stderr, "Impossibile creare segmento condiviso\n");
err= errno;
fprintf (stderr, "Errore %d\n",err);
exit (-1);}
//////////// attacco memoria condivisa a spazio processo
shmatt = shmat ( shmid, (void *)0 ,0);
if (shmatt == (void *) -1) { fprintf (stderr, "Impossibile modificare spazio indirizzi processo\n");
err= errno;
fprintf (stderr, "Errore %d\n",err);
exit (-2);}
new_area = (int *) shmatt;
///////////////////////////////////// begin fork /////////////////////////////////////////////////////////
int pid;
pid = fork();
if ( pid == 0) {
//precritical section
////////////////////////////// begin critical section child process
//critical section
///////////////////////////// end critical section child process
// post critical section
shmdet = shmdt (shmatt);
if (shmatt == (void *)-1) { fprintf (stderr, "Impossibile detachare memoria condivisa\n");
err= errno;
fprintf (stderr, "Errore %d\n",err);
exit (-3);}
} else {
//precritical section
////////////////////////////// begin critical section parent process
//critical section
///////////////////////////// end critical section parent process
// post critical section
waitpid(-1,&status,0);
shmdet = shmdt (shmatt);
if (shmatt == (void *)-1) { fprintf (stderr, "Impossibile detachare memoria condivisa\n");
err= errno;
fprintf (stderr, "Errore %d\n",err);
exit (-4);}
shmcontrol = shmctl (shmid,IPC_RMID,NULL );
if (shmcontrol == -1) { fprintf (stderr, "Impossibile settare memoria condivisa per eliminazione\n");
err= errno;
fprintf (stderr, "Errore %d\n",err);
exit (-5);}
}
return 0;
}
Comment