diff options
Diffstat (limited to 'sync/reader.c')
-rw-r--r-- | sync/reader.c | 26 |
1 files changed, 19 insertions, 7 deletions
diff --git a/sync/reader.c b/sync/reader.c index 66ee57b..929eba1 100644 --- a/sync/reader.c +++ b/sync/reader.c @@ -4,11 +4,15 @@ #include <stdlib.h> #include <sys/ipc.h> #include <sys/select.h> +#include <sys/sem.h> #include <sys/shm.h> #include <sys/types.h> #include <time.h> #include <unistd.h> +#define NSEM 3 +#define KEY 52 + char *mem; void quit(signum) @@ -22,10 +26,10 @@ int main(argc, argv) int argc; char **argv; { -printf("\tR STARTING\n"); - int shmid, i, pid, id; + int shmid, semid, i, pid, id; char filename[50]; FILE *fd; + struct sembuf sb; if (argc < 2) { printf("usage: reader [id]\n"); @@ -33,7 +37,6 @@ printf("\tR STARTING\n"); } id = atoi(argv[1]); -printf("\tR%d. started...\n", id); if ((shmid = shmget(52, 1<<14, IPC_CREAT | 0666)) == -1){ @@ -45,12 +48,16 @@ printf("\tR%d. started...\n", id); perror("shmat"); exit(1); } + + if ((semid = semget(shmid, NSEM, 0)) == -1) { + perror("Rsemget: "); + exit(1); + } + signal(SIGQUIT, quit); -printf("\tR%d. SHMID: %d\n", id, shmid); sprintf(filename, "reader.%d", id); -printf("\tR%d. opening file \"%s\"...\n", id, filename); fd = fopen(filename, "a"); if (!fd) { @@ -60,7 +67,9 @@ printf("\tR%d. opening file \"%s\"...\n", id, filename); srand(time(NULL)); while (1) { -printf("\tR%d. reading...\n", id); + sb.sem_num = 0; sb.sem_op = -1; sb.sem_flg = 0; + semop(semid, &sb, 1); + for (i = 0; i < 1<<14; i++) { fprintf(fd, "%c", *(mem + i)); fflush(fd); @@ -68,7 +77,10 @@ printf("\tR%d. reading...\n", id); fprintf(fd, "\n"); fflush(fd); -printf("\tR%d. waiting...\n", id); + sb.sem_op = 1; + semop(semid, &sb, 1); + + sleep(rand() % (id + 1)); } } |