这是我的代码,其中有一个父亲使用fork()创建15个进程,然后他启动计时器。创建后,所有孩子都必须与自己(而不是与父亲)互动,直到计时器停止。此后,他们解锁信号量,父亲开始履行职责,然后终止。我在信号量上遇到了一些问题。当孩子拥有锁时,程序将永远等待。
#define NUM_SEMS 2 //number of semaphores
#define PADRE 0 //father semaphore
#define ALUNNI 1 //child semaphore
#define POP_SIZE 15 //number of child
/*more defines*/
/*shared memory initialization*/
/* Create a shared memory area */
mem_Id = shmget(IPC_PRIVATE, sizeof(*corso), 0600);
TEST_ERROR;
shm_id = mem_Id;
/* Attach the shared memory to a pointer */
corso = shmat(mem_Id, NULL, 0);
TEST_ERROR;
corso->cur_idx = 0; /* init first counter */
shm_print_stats(2, mem_Id);
/* Create a semaphore to synchronize the start of all child
* processes */
printf("Creo SEMAFORI\n");
sem_Id = semget(IPC_PRIVATE, NUM_SEMS, 0600);
TEST_ERROR;
/* Sem 0 to syncronize the start of child processes */
semctl(sem_Id, 0, SETVAL, 0);
// TEST_ERROR;
#ifdef SHMEMORY
semctl(sem_Id, 1, SETVAL, 1); //puoi disattivare il semaforo
#endif
/* Initialize the common fields */
sops.sem_num = 0; /* check the 0-th semaphore */
sops.sem_flg = 0; /* no flag */
printf("SUBITO PRIMA DELL'INIT\n");
init();
kid_pids = malloc(POP_SIZE*sizeof(*kid_pids));
for (i=0; i<POP_SIZE; i++) {
matricola = maxMin_rand(99999, 10000);
//printf("\nSono qui3\n");
switch (kid_pids[i] = fork()) {
case -1:
/* Handle error */
TEST_ERROR;
break;
case 0:
/* Wait for the green light */
sops.sem_op = -1;
semop(sem_Id, &sops, 1);
while(exit_loop == 0 || exit_loop == 1){
/*child code*/
}
unlockSem(sem_Id, ALUNNI);
}
//sleep(1);
exit(0);
break;
default:
break;
}
}
/*
* All child processes are attached. Then the shared memory
* can be marked for deletion.
*/
while (shmctl(mem_Id, IPC_RMID, NULL)) { TEST_ERROR; }
/* Inform child processes to start */
sops.sem_op = POP_SIZE;
semop(sem_Id, &sops, 1);
/* Waiting for all child processes to terminate */
while ((child_pid = wait(&status)) != -1) {
dprintf(2,"PID=%d. Sender (PID=%d) terminated with status 0x%04X\n",
getpid(),
child_pid,
status);
}
/* Now the semaphore may be deallocated */
semctl(sem_Id, 0, IPC_RMID);
我希望使用父进程初始化共享内存并创建15个子进程,因为父进程在信号量PADRE上获得了LOCK。然后他解锁信号量,这是孩子的转机。他们与自己进行交互以更新共享内存。计时器到期后,父亲重新获得LOCK,他打印共享内存的一些记录,最后终止。
我一定使用了错误的信号量,也许为父亲设置了一个信号量,为孩子们设置了另一个。如果仅用一个信号量就可以解决,那就没问题了。