我有一个父进程,它在循环中使用fork创建了16个子进程。最终,每个孩子都会发送一个SIGUSR1信号,该信号由父进程中的处理函数处理。C - 多个孩子 - 信号互相覆盖
我的问题是这样的 - 有些孩子发送的信号,而来自另一个孩子的信号处理。我读到处理函数然后停止并处理新信号,忽略它正在处理的当前信号。
我试图通过在处理函数的开始处发送:kill(0,SIGSTOP)
来解决此问题,但看起来像停止父进程一样。有没有办法将这个信号发送给孩子?
如果不可能,我的目标是否可以使用wait, waitpid and kill
实现?
添加下面的代码,我离开了东西一样检查读取的返回值,开放等
处理函数:
void my_signal_handler(int signum, siginfo_t* info, void* ptr)
{
kill(0, SIGSTOP);
int sonPid = info->si_pid;
char* pipeName = malloc(14 + sizeof(int));//TODO ok?
sprintf(pipeName, "//tmp//counter_%d" , (int) sonPid); //TODO double //?
size_t fdPipe = open(pipeName, O_RDONLY);
int cRead;
int countRead = read(fdPipe,&cRead,sizeof(int));
COUNT+= cRead;
kill(0, SIGCONT);
return;
}
创建子进程:
struct sigaction new_action;
memset(&new_action, 0, sizeof(new_action));
new_action.sa_handler = my_signal_handler;
new_action.sa_flags = SA_SIGINFO;
if(0 != sigaction(SIGUSR1, &new_action, NULL))
{
printf("Signal handle registration failed. %s\n", strerror(errno));
return -1;
}
for(int i=0; i<16; i++){
pid_t cpid = fork();
if(cpid == 0) // child
{
execv("./counter",argvv); // some arguments to the function
printf("execv failed: %s\n", strerror(errno));
return -1;
}
else{
continue;
}
儿童的计数器程序,总之它计数字符counc
在文件的某些部分的外观,然后打印到一个管道:
int main(int argc, char** argv){
int counter = 0;
char counc = argv[1][0];
char* filename = argv[2];
off_t offset = atoll(argv[3]);
ssize_t length = atoll(argv[4]);
int fd = open(filename, O_RDWR | O_CREAT);
char* arr = (char*)mmap(NULL, length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset);
for(int i=0; i<length; i++){
if(arr[i] == counc){
counter++;
}
}
pid_t proid = getpid();
pid_t ppid = getppid();
char* pipeName = malloc(14 + sizeof(pid_t));
sprintf(pipeName, "//tmp//counter_%d" , (int) proid);
size_t fdPipe = mkfifo(pipeName, 0777);
int didopen = open(pipeName,O_WRONLY);
size_t wrote = write(fdPipe,&counter , 1);
if(wrote < 0){
printf(OP_ERR, strerror(errno));
return errno;
}
kill(ppid, SIGUSR1);
//close the pipe and unmap the array
return 1;
}
请将您的代码作为正确的[最小,完整和可验证示例](https://stackoverflow.com/help/mcve)(请仔细阅读该页面)。 – Arash
我认为在这种情况下可以解释一下,但我会尽快添加一个代码示例。 – Gray
这是不正确的,被处理的信号被阻塞直到处理程序完成,所以如果它们都发送相同的信号,你应该没问题。一些代码将有助于识别您的**真实**问题。顺便说一句,保持处理程序简短,只需设置标志并在信号处理程序外执行复杂的处理。 –