我正在研究读写器问题。算法明智,我相信解决方案是好的。我面临的唯一问题是使用 xterm 打开多个读取器/写入器窗口。当我运行程序时,它进入了一个无限循环,它使整个系统崩溃。它还打开多个 xterm 窗口。这可能很愚蠢和简单,但我似乎无法弄清楚为什么?从昨天开始我就一直在思考这个问题。我该如何解决这个问题?可疑的冲突区域以 ** 注释突出显示...
#include <unistd.h> /* Symbolic Constants */
#include <sys/types.h> /* Primitive System Data Types */
#include <errno.h> /* Errors */
#include <stdio.h> /* Input/Output */
#include <stdlib.h> /* General Utilities */
#include <pthread.h> /* POSIX Threads */
#include <string.h> /* String handling */
#include <semaphore.h> /* Semaphore */
//Global Variablels
int rc = 0;
int wc = 0;
sem_t m1, m2, m3, w, r; //Semphore
int reader() {
sem_wait(&m3);
sem_wait(&r);
sem_wait(&m1);
rc++;
if(rc == 1) sem_wait(&w);
sem_post(&m1);
sem_post(&r);
sem_post(&m3);
system("xterm -e ./read");
//execlp("xterm", "-e", "./ahor2r", NULL);
sem_wait(&m1);
rc--;
if(rc == 0) sem_post(&w);
sem_post(&m1);
return 0;
}
int writer() {
sem_wait(&m2);
wc++;
if(wc == 1) sem_wait(&r);
sem_post(&m2);
sem_wait(&w);
//system("xterm -e ./write"); //writing is performed
execlp("xterm", "-e", "./ahor2w", NULL);
sem_post(&w);
sem_wait(&m2);
wc--;
if(wc == 0) sem_post(&r);
sem_post(&m2);
return 0;
}
int main() {
int ch;
sem_init(&m1, 0, 1);
sem_init(&m2, 0, 1);
sem_init(&m3, 0, 1);
sem_init(&w, 0, 1);
sem_init(&r, 0, 1);
/*****************************************************************************
**********infinite loop*******************************************************/
while(1) {
printf("\n\nEnter your option\n\n1> Create Reader\n2> Create Writer\n 3> Exit\n\t");
scanf("%d", &ch);
if(ch == 1)
switch(fork()) {
case -1:
perror("Cannot fork a new reader process\n");
break;
case 0:
reader();
}
else if (ch == 2)
switch(fork()) {
case -1:
perror("Cannot fork a new reader process\n");
break;
case 0:
writer();
}
else if (ch == 3) {
sem_destroy(&m1);
sem_destroy(&m2);
sem_destroy(&m3);
sem_destroy(&w);
sem_destroy(&r);
return 0;
}
else printf("INVALID OPTION - no action taken\n");
}
/*****************************************************************************
*****************************************************************************/
return 0;
}