c - 使用 ptrace 停止或杀死进程中的线程?
问题描述
从另一个进程中杀死一个进程中的特定线程。
下面是我的代码:
ptrace(PTRACE_ATTACH,threadID,NULL,NULL);
停止整个过程,但我只想停止一个特定的线程。
您能否为我提供一些有关如何进行的指示?
解决方案
您可以按照以下步骤操作:
1)创建一个管道并初始化它。
2) 为特定信号创建信号处理程序,信号处理程序应执行最少的操作。在这种情况下,我会将“signum”写入管道的写入端。
3)创建一个线程将在轮询时被阻塞,并且它需要从管道的读取端读取数据。
4)然后我将忽略上面在其他线程中使用的信号。
5)然后继续主线程,这里我有一个无限循环。
6) 现在您可以运行程序并使用进程 ID 从控制台发送信号。例如,假设进程id是24566,那么我将发送信号如下:
kill -n 16 24566
这只会杀死特定的线程而不是完整的程序。
你可以在下面找到我写的程序:
#include <pthread.h>
#include <stdio.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/poll.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#define ERR -1
int pipefd[2] = {0, 0};
void signal_handler(int signum)
{
printf("signal handler");
if (ERR == write(pipefd[1], &signum, sizeof(signum)))
printf("errno: %d", errno);
}
void initializePipeAndAddSignalHandler()
{
if (ERR == pipe(pipefd))
{
printf("pipe2 returned an error: %s", strerror(errno));
exit(EXIT_FAILURE);
}
else
{
if (SIG_ERR == signal(SIGUSR1, signal_handler))
{
printf("Enabling signal Handling to SIGUSR1 failed: %s", strerror(errno));
exit(EXIT_FAILURE);
}
}
}
void *threadfunc(void *arg)
{
int sig = -1;
const int NO_FDS = 1;
struct pollfd fds[NO_FDS];
nfds_t nfds = NO_FDS;
const int PIPE_FD = 0;
fds[PIPE_FD].events = POLLIN | POLLHUP;
fds[PIPE_FD].fd = pipefd[0];
printf("in threadfunc");
while(1)
{
int ret = poll(fds, nfds, -1);
printf("Poll called");
if (ret != ERR)
{
if (POLLIN == (fds[PIPE_FD].revents & POLLIN))
{
if (-1 != read(fds[PIPE_FD].fd, &sig, sizeof(sig)))
{
switch (sig)
{
case SIGUSR1:
{
printf("received sigusr1");
return NULL;
}
default:
{
printf("UnKnown Signal received = %d", sig);
break;
}
}
}
}
}
}
}
int main()
{
int sig_return;
sigset_t set;
initializePipeAndAddSignalHandler();
pthread_t tid;
if(pthread_create(&tid, NULL, &threadfunc, NULL))
{
fprintf(stderr, "Error creating thread\n");
return 1;
}
sigemptyset(&set);
sigaddset(&set, SIGUSR1);
sig_return = pthread_sigmask(SIG_BLOCK, &set, NULL);
if (sig_return != 0)
printf("Setting sigmask failed");
while (1)
{
printf("\nmain thread running\n");
sleep (1);
}
printf("killed");
}
推荐阅读
- php - 如何解析客户端-> __getLastResponse?
- azure-active-directory - 当用户尝试链接社交帐户并单击取消时,有没有办法让用户保持登录到 Azure ADB2C?
- objective-c - Admob 关闭按钮位于 iPhone 12 的安全区域上方
- python - Keras,简单的模型,形状不兼容,但为什么呢?
- javascript - 在执行更多代码之前,如何等待可观察对象更新?
- python - 如何将类变量作为字典返回?
- firebase - 为 Firebase 项目配置 CI 时,我应该使用 Firebase 令牌还是 GCP 服务帐户密钥?
- apache - URL 路径和 .htacces 重定向问题
- java - Java to Kotlin 接口方法名和字段名 colsion (Java, Kotlin mix)
- reactjs - 如何在 React 中将继承转化为组合(示例)?