我目前正在学习Linux操作系统下的C语言信号.
我有一个父进程,它希望将一个名为struct Data
的整值 struct 发送到它Forking 的子进程-使用siginfo_t struct ,当我们使用sigcation定义信号处理程序时,它是信号处理程序的参数:void handler(int, siginfo_t*, void*)
父进程定义union sigval
,并将联合中的sival_ptr
字段设置为
(void*) data
,其中数据是包含两个整数的struct Data
.
然后家长使用sigqueue(child_pid, SIGUSR1, my_sigval)
子进程使用我前面提到的sigaction,并且它使用标志SA_SIGINFO
为SIGUSR 1信号设置信号处理程序.
在子代码的信号处理程序内部,我定义了指针struct Data* data
并做这行:data = (struct Data*) (si->si_value.sival_ptr)
然后我try 打印我从父母发送的数据.
我得到的行为是,子进程在打印struct Data data
内的值之前退出,并且该行之前的所有内容都会按照预期执行并打印在屏幕上.
我哪里做错了?我是否没有正确地从家长那里传递指针到struct Data
?
或者我在子信号处理器功能内的铸造过程中做错了什么?
以下是代码:
父母 :
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#define MY_SIGNAL SIGUSR1
// Define a structure to hold two integers
struct Data {
int value1;
int value2;
};
int main() {
// Prepare data structure
struct Data* data = (struct Data*) malloc(sizeof(struct Data));
data->value1 = 10;
data->value2 = 20;
// Fork a child process
pid_t pid = fork();
if (pid == -1) {
perror("fork failed");
return 1;
} else if (pid == 0) { // Child process
// Child process logic
execlp("./c2","c2", NULL);
//
} else { // Parent process
// Sending the signal with a pointer to the data structure
union sigval value;
value.sival_ptr = (void*) data;
// value.sival_int = 7;
sleep(1);
sigqueue(pid, MY_SIGNAL, value);
sleep(1);
}
wait(NULL);
return 0;
}
子元素:
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#define MY_SIGNAL SIGUSR1
// Define a structure to hold two integers
struct Data {
int value1;
int value2;
};
// Function to handle the signal
void handler(int sig, siginfo_t *si, void *unused) {
printf("Received signal: %d\n", sig);
// printf("Received signal value: %d\n", si->si_value.sival_int);
struct Data* data;
data = (struct Data*)(si->si_value.sival_ptr);
printf("Received values: %d, %d\n", data->value1, data->value2);
// Copy the received data into the allocated memory
}
int main() {
// Set up signal handler
struct sigaction sa;
sa.sa_sigaction = handler;
sa.sa_flags = SA_SIGINFO;
sigemptyset(&sa.sa_mask);
sigaction(MY_SIGNAL, &sa, NULL);
pause();
return 0;
}