在Linux中,可以使用ptrace系统调用来捕获进程收到的信号。下面是一个简单的示例代码,演示如何使用ptrace来捕获进程的信号:
#include <stdio.h>
#include <stdlib.h>
#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
int main() {
pid_t child;
int status;
child = fork();
if (child == 0) {
// Child process
printf("Child process is running...\n");
sleep(5);
printf("Child process sending SIGUSR1 signal...\n");
kill(getpid(), SIGUSR1);
exit(0);
} else {
// Parent process
printf("Parent process is running...\n");
ptrace(PTRACE_ATTACH, child, NULL, NULL);
waitpid(child, &status, 0);
if (WIFSTOPPED(status)) {
int signal = WSTOPSIG(status);
printf("Child process stopped by signal %d\n", signal);
// Resume child process
ptrace(PTRACE_CONT, child, NULL, signal);
}
waitpid(child, &status, 0);
if (WIFEXITED(status)) {
printf("Child process exited with status %d\n", WEXITSTATUS(status));
}
ptrace(PTRACE_DETACH, child, NULL, NULL);
}
return 0;
}
在这个示例中,父进程使用ptrace(PTRACE_ATTACH)来附加到子进程,然后等待子进程接收到信号。当子进程接收到信号时,父进程会收到一个SIGCHLD信号,并调用waitpid()来获取子进程的状态,然后使用ptrace(PTRACE_CONT)来继续执行子进程。最后,父进程使用ptrace(PTRACE_DETACH)来分离子进程。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: Linux解压zip报错怎么解决