#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
/**
* 杀死指定进程名的所有进程
* @param process_name 要杀死的进程名
* @return 成功杀死的进程数量,-1表示执行错误
*/
int kill_process_by_name(const char *process_name) {
FILE *fp;
char buffer[1024];
char cmd1[256];
pid_t pid;
int kill_count = 0;
if (process_name == NULL || strlen(process_name) == 0) {
fprintf(stderr, "Error: process name cannot be empty\n");
return -1;
}
sprintf(cmd1,"ps aux | grep %s | grep -v grep | head -1 | awk '{print $1}'",process_name);
// 使用ps aux命令获取所有进程信息
fp = popen(cmd1, "r");
if (fp == NULL) {
perror("popen failed");
return -1;
}
printf("Searching for process: %s\n", process_name);
// 跳过标题行
if (fgets(buffer, sizeof(buffer), fp) == NULL)
{
pclose(fp);
return 0; // 没有进程信息
}
myDebug("get buffer is:%s\n",buffer);
pid=atoi(buffer);
myDebug("kill pid=%d\n",pid);
if (kill(pid, SIGKILL) == 0)
{
printf("Successfully killed process %s (PID: %d)\n", process_name, pid);
kill_count++;
}
else
{
perror("kill failed");
}
pclose(fp);
return kill_count;
}
linux下实现杀死进程c程序
最新推荐文章于 2025-12-06 19:52:12 发布
305

被折叠的 条评论
为什么被折叠?



