操作系统的编程作业,思路完全按照书上对银行家算法的描述,编译能够通过,但运行时会出错,得不到正确的结果。
我也是受同学所托,希望蝈蝈们能帮我看一下,快崩溃了
估计是那个find函数有点问题,即安全性算法的第二步:从进程集合中找到一个能满足条件Finish【i】=false;Need[i,j]<=Work[j];的进程,找到返回1,否则返回0;
#include <stdio.h>
#define TRUE 1
#define FALSE 0
int available[256], work[256], finish[256];
int max[256][256], allocation[256][256], need[256][256];
int i, j, temp;
int find(int i, int j)
{
int row, n, count;
for (row = 0; row < i; row++) {
count = 0;
if (finish[row] == FALSE) {
for (n = 0; n < j; n++)
if (need[row][n] <= work[n])
count++;
else
break;
}
if (count == j) {
temp = row;
return 1;
}
}
return 0;
}
void security(int id)
{
int n, cnt;
for (n = 0; n < j; n++) {
work[n] = available[n];
}
for (n = 0; n < i; n++) {
finish[n] = FALSE;
}
while (find(i, j) == 1) {
for (n = 0; n < j; n++) {
work[n] += allocation[temp][n];
}
finish[temp] = TRUE;
}
for(n = 0; n < i; n++)
if (finish[n] == TRUE)
cnt++;
//printf("\n%d", cnt);
if (cnt == i)
printf("\nSystem can allocate the resource to the process P%d.\nIt's safe!\n", id);
else
printf("\nSystem can NOT allocate the resource to the process P%d.\nIt's NOT safe!\n", id);
}
void banker(int *request, int id)
{
int n = 0;
while (n < j) {
if (request[n] <= need[id][n])
n++;
else {
printf("\nP%d is asking for more resorces than it needs!\n", id);
return;
}
}
n = 0;
while (n < j) {
if (request[n] <= available[n])
n++;
else {
printf("\nP%d is asking for more resorces than it can get!\n", id);
return;
}
}
for (n = 0; n < j; n++) {
available[n] -= request[n];
allocation[id][n] += request[n];
need[id][n] -= request[n];
}
security(id);
}
main()
{
int n, n1, n2, id, request[256];
printf("please input the number of process: i = ");
scanf("%d", &i);
printf("\nplease input the number of resource: j = ");
scanf("%d", &j);
printf("\nplease input the array of Available[]:\n");
for (n = 0; n < j; n++)
scanf("%d", &available[n]);
printf("\nplease input the array Max[][]:\n");
for (n1 = 0; n1 < i; n1++)
for (n2 = 0; n2 < j; n2++)
scanf("%d", &max[n1][n2]);
printf("\nplease input the array Allocation[][]:\n");
for (n1 = 0; n1 < i; n1++)
for (n2 = 0; n2 < j; n2++)
scanf("%d", &allocation[n1][n2]);
//the array need[][]
for (n1 = 0; n1 < i; n1++)
for (n2 = 0; n2 < j; n2++)
need[n1][n2] = max[n1][n2] - allocation[n1][n2];
printf("\nplease input the ID of process which is asking for resource: id = ");
scanf("%d", &id);
printf("\nplease input the array of Request[]:\n");
for (n = 0; n < j; n++)
scanf("%d", &request[n]);
banker(request, id);
}
[ 此贴被康师傅在2007-06-18 18:27重新编辑 ]