c - 共享内存中的简单检查返回 SIGSEGV 错误 008b
问题描述
我在 C 中实现了一个共享内存,让分叉的孩子相互交流,这是一个最小、完整和可验证的示例:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#define SHMEMORY
#define NUM_SEMS 2
#define LOCK \
sops.sem_num = 1; \
sops.sem_op = -1; \
semop(sem_Id, &sops, 1);
#define UNLOCK \
sops.sem_num = 1; \
sops.sem_op = 1; \
semop(sem_Id, &sops, 1);
#define TEST_ERROR if (errno) {dprintf(STDERR_FILENO, \
"%s:%d: PID=%5d: Error %d (%s)\n", \
__FILE__, \
__LINE__, \
getpid(), \
errno, \
strerror(errno));}
#define POP_SIZE 100 //number of child
#define TRUE 1
struct shared_data {
/* index where next write will happen */
unsigned long cur_idx;
int invite_sent[POP_SIZE][POP_SIZE];
};
static void init();
static int invite_sent_check(int stud);
int maxMin_rand(int max,int min);
void handle_signal(int sig);
int sim_time = 10;
unsigned long next_num;
struct sembuf sops;
pid_t *kid_pids;
int mem_Id, sem_Id;
int main() {
int i = 0;
int j = 0;
int status, cur_i;
struct shared_data* corso;
pid_t child_pid, my_pid;
int stud = 0;
int exit_loop = 0;
/*********************************************************/
struct sigaction sa;
sigset_t my_mask;
/* handler SIGALRM
*/
sa.sa_handler = handle_signal;
sa.sa_flags = 0;
sigemptyset(&my_mask);
sa.sa_mask = my_mask;
sigaction(SIGALRM, &sa, NULL);
/**********************************************************/
mem_Id = shmget(IPC_PRIVATE, sizeof(*corso), 0600);
TEST_ERROR;
/* Attach the shared memory to a pointer */
corso = shmat(mem_Id, NULL, 0);
TEST_ERROR;
corso->cur_idx = 0; /* init first counter */
/*********************************************************/
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);
#ifdef SHMEMORY
semctl(sem_Id, 1, SETVAL, 1);
#endif
TEST_ERROR;
sops.sem_num = 0; /* check the 0-th semaphore */
sops.sem_flg = 0; /* no flag */
init();
kid_pids = malloc(POP_SIZE*sizeof(*kid_pids));
for (i = 0; i < POP_SIZE; i++) {
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){
LOCK;
if(exit_loop == 0){
stud = corso->cur_idx;
printf("%d %d\n",stud,getpid());
corso->cur_idx++;
exit_loop = 1;
}
if(invite_sent_check(stud) == 1){
}
UNLOCK;
}
exit(0);
break;
default:
break;
}
}
alarm(sim_time);
while (shmctl(mem_Id, IPC_RMID, NULL)) { TEST_ERROR; }
sops.sem_op = POP_SIZE;
semop(sem_Id, &sops, 1);
/* Waiting for all child POP_SIZEesses 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);
exit(0);
}
static void init(){
printf("INIT\n");
struct shared_data * corso;
corso = shmat(mem_Id, NULL, 0);
corso->cur_idx=0;
int r, q, j;
j = 0;
q = 0;
while(j < POP_SIZE){
q = 0;
while(q < POP_SIZE){
corso->invite_sent[j][q] = -1;
q++;
}
j++;
}
}
int maxMin_rand(int max, int min){
int reset;
int randomics=12345;
int w=0;
while(w<reset) {
randomics++;
w++;
}
next_num = next_num+randomics;
next_num = next_num*1103515245 +12345;
unsigned int result=(unsigned int) ((next_num*65536)%(max+1))+min;
int reload;
w=0;
while(w<reload) {
next_num++;
w++;
}
return result;
}
static int invite_sent_check(int stud){
struct shared_data * corso;
corso = shmat(mem_Id, NULL, 0);
int i = 0;
int q = 0;
while(i < POP_SIZE){
if(i == stud){
q = 0;
while(q < POP_SIZE){
if(corso->invite_sent[i][q] != -1){
return 1;
}
q++;
}
}
i++;
}
return 0;
}
void handle_signal(int signal){
int child_pid;
int status;
struct shared_data * corso;
corso = shmat(mem_Id, NULL, 0);
switch (signal) {
case SIGALRM:
for(int i = 0; i < POP_SIZE; i++){
kill(kid_pids[i], SIGKILL);
}
while (shmctl(mem_Id, IPC_RMID, NULL)) {
TEST_ERROR;
}
while ((child_pid = wait(&status)) != -1) {
dprintf(2,"PID=%d. Sender (PID=%d) terminated with status 0x%04X\n",
getpid(),
child_pid,
status);
}
semctl(sem_Id, 0, IPC_RMID);
exit(0);
break;
}
}
只要计时器运行(sim_time = 10),分叉的孩子就会保持 LOCK 和 UNLOCK。然后 SIGNAL_HANDLER 杀死所有的孩子,并终止。我不断从一个以状态 008B 终止并停止他的“兄弟”的 RANDOM 子进程收到 SIGSEGV 错误,直到处理程序杀死所有其他进程。据我所知,这个错误涉及共享内存中的指针,对吗?或者我错过了/我写了一些真正错误的东西?即使是这个检查 INVITE_SENT 矩阵中是否有至少 1 个值与 -1 不同的小方法也会导致崩溃,而不是只返回 0。感谢您的宝贵时间。
解决方案
我一直无法在本地重现段错误,并且 Valgrind 没有检测到任何无效的内存访问。段错误还有其他可能的原因,但它们并不常见。由于无法在本地重现该问题,我无法确定其来源,但代码中存在许多问题,大多是次要问题。
似乎与您的问题相关的唯一问题是您在函数中对共享内存段的冗余附加invite_sent_check()
,特别是考虑到您使用返回值shmat()
而不检查它((void*)-1
失败时返回)。诸如此类的冗余附件是明确允许的,但调用者只需将其现有指针传递给该段的原始附件点会更清晰、更有效。此外,如果您在该函数中形成本地附件,那么您必须确保在函数返回之前再次分离。不这样做很可能是问题的根源,因为由此产生的许多附件的元数据和地址空间保留可能会耗尽可用资源。
其他问题包括
dprintf()
不是异步信号安全的,而是从信号处理程序(显式和通过宏TEST_ERROR
)调用。shmat()
不是异步信号安全的,但它是从信号处理程序中调用的。此外,这似乎没有必要,因为处理程序中没有使用新的段附件。此外,它也不是分离的。semctl()
不是异步信号安全的,但它是从信号处理程序中调用的。exit()
不是异步信号安全的,但它是从信号处理程序中调用的。您可以使用_Exit()
or_exit()
代替,但似乎该处理程序应该完全退出程序,因为主进程似乎还有其他要清理的工作。Considering all the things you seem to want to do when you receive the
SIGALRM
, many of them not async-signal-safe, you should consider usingsigsupend()
to receive the signal synchronously, and afterward calling a regular function to do that work. If you go that direction, then the safest, most reliable approach would involve first blockingSIGALRM
before stting your alarm, then passing a signal mask tosigsuspend()
that allows that signal. That will prevent any chance of the signal being delivered before the process is ready for it.Function
init()
redundantly attaches the shared memory segment. This is allowed, but it would be better form for the caller to just pass a pointer to thestruct shared_data
that is to be initialized. This function, too, fails to detach.如果您想通过检查来检查错误
errno
,则必须确保在要检查的调用之前将其设置为 0(并在执行其他任何操作之前立即对其进行测试)。但是,更好的做法是使用函数的返回值来检测是否发生了错误,并errno
仅依赖于辨别是哪一个。函数的名称和签名
maxMin_rand()
表明它旨在返回一个介于max
and之间的数字min
,但看起来它可以返回一个与 一样大的数字max + min
。
推荐阅读
- python - 如何从json中删除空引号和外花括号
- javascript - 如何将多个 if 语句重构为更简洁的代码?
- json - 使用 JQ 将 json 属性值级联到所有为空的后代
- django - Django 频道获取当前频道
- python - 在 Python 中使用 assert 检查条件是否为 False
- java - 我无法使用 getGraphics() 方法绘制任何东西
- javascript - Safari 从内存缓存中获取图像的时间太长
- spring-integration - Spring Integration:自上次轮询以来仅摄取新文件
- java - 将十进制值转换为二进制时遇到问题
- python - 无法应用一个非常简单的 json.dumps 解决方案,为什么?