在Linux中,可以使用ptrace系统调用来捕获进程收到的信号。下面是一个简单的示例代码,演示如何使用ptrace来捕获进程的信号:
#include#include #include #include #include #include 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)来分离子进程。