wait()获得被中断的系统调用

  • 本文关键字:中断 系统调用 wait c
  • 更新时间 :
  • 英文 :


我认为wait()函数将等待直到进程完成,但是它接收到一个信号-1。有人知道问题的原因吗?也许问题出在我的共享记忆上?所以我试着做一个调试,在调试模式下没有问题,就像我在正常模式下运行我的代码一样。


#include <stdio.h>
#include <stdlib.h>
#include <sys/shm.h>
#include <unistd.h>
#include <errno.h>
#define PROCESSES 3
struct shdata
{
int x;
};
void childf(int shared_memory, int index)
{
// connect shared memory
struct shdata* shm = (struct shdata*)shmat(shared_memory, NULL, 0);
if(shm == (void*)-1)
{
perror("shmat");
exit(0);
}

// initialize x as 0
if(index == 0)
{
shm->x = 0;
}

// increment x
shm->x++;

//show x
printf("Proces %d: x = %dn", index, shm->x);

// disconnect shared memory
if(shmdt(shm) == -1)
{
perror("shmdt");
exit(0);
}

// end child process
exit(0);
}
int main(int argc, const char * argv[]) {

// create shared memory
int shared_memory = shmget(IPC_PRIVATE, 4096, 0600 | IPC_CREAT | IPC_EXCL);
if(shared_memory == -1)
{
perror("shmget");
return 1;
}

// create child processes
for (int i = 0; i < PROCESSES; i++)
{
int pid = fork();
if(pid == -1)
{
perror("fork");
return 5;
}
if(pid == 0)
{
childf(shared_memory, i);
}
}

// wait for child processes
for(int i = 0; i < PROCESSES; i++)
{
int wait_res = wait(NULL);
if(wait_res < 0)
{
perror("wait");
return 6;
}
}

// delete shared memory
int delete_memory = shmctl(shared_memory, IPC_RMID, NULL);
if(delete_memory == -1)
{
perror("shmctl");
return 4;
}

return 0;
}

这就是我得到的:

Proces 0: x = 1 Proces 1: x = 2 Proces 2: x = 3 wait: Interrupted system call Program ended with exit code: 6

但有时我没有收到这个错误。那么问题是什么呢?

我预期:

Proces 0: x = 1 Proces 1: x = 2 Proces 2: x = 3 Program ended with exit code: 0

一个本来良性的信号总是可以中断wait(和其他阻塞系统调用)。如果你对信号不感兴趣,那就继续等待。

而不是

wait_res = wait(NULL);

使用:

while ((wait_res = wait(NULL)) == -1) {  
if (errno != EINTR) break;
}

最新更新