#include #include #include #include #include #include "binSem.h" static int sem_id; int main(int argc, char *argv[]) { int i; int pause_time; char op_char = 'C'; FILE *fd; char name[]="temp2.txt"; srand((unsigned int)getpid()); sem_id = start_semvalue(1234); if (!set_semvalue(sem_id,1)) { fprintf(stderr, "Failed to initialize semaphore\n"); exit(EXIT_FAILURE); } if (fork() == 0){ for(i = 0; i < 10; i++) { if (!semaphore_p(sem_id)) exit(EXIT_FAILURE); /* start of critical section */ fd = fopen(name, "a"); fprintf(fd, "%c", op_char);fflush(stdout); pause_time = rand() % 3; sleep(pause_time); fprintf(fd, "%c", op_char);fflush(stdout); fclose(fd); /* end of critical section */ if (!semaphore_v(sem_id)) exit(EXIT_FAILURE); pause_time = rand() % 2; sleep(pause_time); } exit(0); } /* we're in the parent's code */ op_char = 'P'; for(i = 0; i < 10; i++) { if (!semaphore_p(sem_id)) exit(EXIT_FAILURE); /* start of critical section */ fd = fopen(name, "a"); fprintf(fd, "%c", op_char);fflush(stdout); pause_time = rand() % 3; sleep(pause_time); fprintf(fd, "%c", op_char);fflush(stdout); fclose(fd); /* end of critical section */ if (!semaphore_v(sem_id)) exit(EXIT_FAILURE); pause_time = rand() % 2; sleep(pause_time); } for (i = 0; i < 2; i++) wait(NULL); printf("\n%d - finished\n", getpid()); del_semvalue(sem_id); exit(EXIT_SUCCESS); }