在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)來分離子進程。