c - C - 使用信号量同步错误
问题描述
这是我的代码,其中有一个父亲使用 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,他打印了一些共享内存的记录,最后终止。
我一定是用错了信号量,也许为父亲设置一个信号量,为孩子设置另一个信号量太多了。如果只用一个信号量就可以修复它,那没关系。
解决方案
推荐阅读
- javascript - change menu and div element on multiple dropdown value
- python - 如何通过命令行覆盖 env vars set dotenv?
- c++ - 我需要一个 Person 类型的循环双向链表,但我不断收到错误,我不明白为什么
- testing - 是否可以播放视频并在 UFT 中记录时间戳?
- python - 以特定格式提取 Excel 数据作为 python 文件的输入
- html - 添加文本会将整个 div 向下移动数百像素?
- captcha - 使用 pytesseract 从验证码中提取文本
- azure-devops - 在 Azure 存储帐户中上传 Blob 时出错
- javascript - 返回 If 语句
- postgresql - pq: "$1" Postgres + go 处或附近的语法错误