5.2.c
c
posted: May, 30th 2012 | jump to bottom
#include "5.1.h" int main(int argc, char *argv[]) { int klucz, nchild, blok, i; if(argc>1) { klucz = atoi(argv[1]); } if(argc>2) { nchild = atoi(argv[2]); } if(argc>3) { blok = atoi(argv[3]); } int pgrp, sem_id, sk; int* count_in = NULL; int* count_out = NULL; count_in = (int*) malloc(nchild*sizeof(int)); count_out = (int*) malloc(nchild*sizeof(int)); pgrp=getpgrp(); sem_id = sem_get(klucz); sem_set(sem_id); printf("\033[2J\033[H"); while(1) { sleep(1); for(i=0;i<nchild;++i) { switch(fork()) { case -1: error("fork"); break; case 0: sk = sem_op(sem_id, -1, blok); if(sk == 1) { fflush(stdout); count_in[i]++; printf("\033[%d;1H Proces [%d] (%d/%d) w sekcji krytycznej",i+1, i, count_in[i], count_out[i]); sleep(1); sem_op(sem_id, 1, blok); printf("\033[%d;1H Proces [%d] (%d/%d) poza sekcja krytyczna",i+1, i, count_in[i], count_out[i]); } else if(sk == 2) { fflush(stdout); count_out[i]++; printf("\033[%d;1H Proces [%d] (%d/%d) czeka na wejscie do sekcji krytycznej",i+1, i, count_in[i], count_out[i]); } break; default: getchar(); sem_del(sem_id); if( killpg(pgrp, 9) == -1) {error("killpg");} break; } } } return 0; }
35 views




