因此,我正在编写一个酒店预订系统,其中我的酒店房间存储在共享内存中,并将有x个客户预订,取消,付款等房间。每个客户都是一个子进程,他们都应同时运行,并尝试对房间进行规定的交易。
这是我对子进程进行分叉的代码:
int pid[10];
for(int i = 0; i < numOfCustomers; i++) {
pid[i] = fork();
if(pid[i] < 0) {
perror("Bad fork");
}
else if(pid[i] == 0) { //is child i (Each customer is a child process)
cout << "CUSTOMER: " << i << endl;
while(!customers[i].transactions.empty()) { //runs until customer finishes all transactions
string op = customers[i].transactions.front();
if(op == "reserve") {
if(sem_wait(semid, 0))
exit(1);
Reserve tempq = customers[i].reservequeue.front();
for(int i = 0; i < tempq.roomcounter; i++) {
int roomnum = tempq.roomqueue.front();
if(shared_memory[roomnum-1].isavailable == true) {
shared_memory[roomnum-1].isavailable = false;
shared_memory[roomnum-1].day = tempq.day;
shared_memory[roomnum-1].month = tempq.month;
shared_memory[roomnum-1].year = tempq.year;
shared_memory[roomnum-1].customer = cust;
}
else {
cout << "Room " << roomnum << " already taken." << endl;
}
tempq.roomqueue.pop();
}
customers[i].reservequeue.pop();
if(sem_signal(semid, 0))
exit(1);
}
else if(op == "cancel") { //not done yet
cout << "cancel" << endl;
}
else if(op == "check") { //not done yet
cout << "check" << endl;
}
else if(op == "pay") { //not done yet
cout << "pay" << endl;
}
customers[i].transactions.pop();
}
exit(0);
}
else { //is parent
}
}
//waits for each process to finish
for (int i = 0; i < numOfCustomers; i++) {
wait(NULL);
}
问题在于,它首先在子级中完成所有操作,然后再在子级2中完成所有操作。进程不是同时运行的,这破坏了拥有共享内存和使用信号量的全部目的。
非常感谢您的帮助。