next up previous contents
Next: MANUEL DE RÉFÉRENCE Up: UTILISATION DE LA LIBRAIRIE Previous: Utilisation dans le système

Exemple

Dans l'exemple ci-dessous, le client se connecte sur un inter serveur standard (key=1000) et lui ordonne de remplir la matrice 1 qui est commune. A la fin de l'exécution, le client affiche une partie du contenu de la matrice partagée avant de libérer la ressource.

#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include "ipcdef.h"

float           *ptr;           /* pointeur sur matrice partagee */
int             semid;          /* descripteur semaphore */
struct block_kw *block;         /* pointeur sur bloc de communication */

extern int      sem_key;        /* identificateur de semaphore */
extern int      block_key;      /* identificateur de memoire pour bloc */
extern int      matrix_key;     /* identificateur de memoire pour matrice */

void
my_handler(sig)
int        sig;
{
        fprintf(stderr,"timeout\n");
}
main()
{
        int         i;
        int         timeout = 4;
        int         stat;

        signal(SIGALRM, my_handler);

        sem_key = 1001;
        block_key = 1002;
        if (init_sem_block(&semid, &block) < 0) {
                printf("erreur allocation semaphore ou bloc");
                exit();
        }

        matrix_key = 1000;
        if (ask_and_init_shm(semid,block,&ptr,0,0) == -1) {
                printf("erreur allocation matrice partagée");
                exit();
        }
        dec_sem_zero(semid, block, timeout);
        ini_shm_block_kw(block);
        put_shm_block_kw(block, "COMMAND", "[1](:,:)=setv(1,nx*ny)");
        block->ackno = 1;
        setval_sem(semid, 2, 1);
        inc_sem(semid, 1);

        if ((stat = wait_for_sem(semid, 2, timeout)) == -2) {
                if (kill(block->pid_server, 0) == 0) {
                        kill(block->pid_server, SIGINT);
                        if (getpid() == block->pid_client) {
                                if (get_cmd_sem(semid, 0, GETVAL) == 0)
                                        inc_sem(semid, 0);
                        }
                }
                exit();
        }

        for(i=0;i<10;i++)printf("%f\n",*(ptr+i));
        inc_sem(semid, 0);
}



WEBER Luc
Mon May 10 13:41:34 MET DST 1999