linux c语言查找指定程序pid

本文介绍了一个用于查找指定名称进程PID的实用程序实现方法。通过调用ps命令并解析其输出,该程序能够返回一个进程中所有匹配项的PID列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

工作上需要向特定进程发送USER2信号,查询进程时找到一个已经封装好的接口,做个备忘。
做为其它程序接口是在程序中加入#include "pidof.h",关联是加上pidof.c就可以了。
如果做为单独程序来使用,将.c中的#include "pidof.h"注掉就能编了。

pidof.h

#ifndef _PIDOF_H_
#define _PIDOF_H_
int lookup_pid(char *name, pid_t *pids, int n); 
#endif

pidof.c

#include <stdio.h>  
#include <string.h>  
#include <sys/types.h>  
#include "pidof.h"

#define PS_COMMAND "ps -ax"  
#define SCAN(buf) (sscanf(buf,"%d %s %s %s %s",pid,s[0],s[1],s[2],cmd) == 5)  

/* Returns number of pid matching process name, or -1 on error */  
int lookup_pid(char *name, pid_t *pids, int n)  
{  
    FILE *fp;  
    char buf[256], cmd[200], s[3][32];  
    pid_t *pid;  

    if ((fp = popen(PS_COMMAND, "r")) == NULL)  
        return -1;  

    pid = pids;  
    while (n > 0 && fgets(buf, sizeof(buf), fp))  
        if (SCAN(buf) && strstr(cmd, name)) /* improve on this simple name check */  
            pid++, n--;  

    fclose(fp);  
    return pid - pids;  
}  

#if #ifndef _PIDOF_H_
int main(int argc, char **argv)  
{  
    char *process;  
    pid_t pids[8];  
    int n, i;  

    if (argc < 2) {  
        printf("Usage: %s process_name  ", argv[0]);  
        return 1;  
    }  
    process = argv[1];  

    if ((n = lookup_pid(process, pids, 8)) == -1) {  
        printf("Error reading pid of %s  ", process);  
        return 2;  
    }  

    printf("%d %s  ", n, process);  
    for (i = 0; i < n; i++)  
        printf("%d  ", pids[ i]);  
    return 0;  
} 
#endif
Linux环境下,使用C语言编写程序查找由`popen()`函数启动的子进程并终止它,需要结合一些系统调用和文件描述符操作。首先,`popen()`创建了一个管道连接,并返回一个指向该连接的FILE *指针。通常,这个连接的双端都是非阻塞的,所以可以获取到子进程的PID。 以下是一个简单的步骤概述: 1. **获取子进程ID**: - 使用`pclose()`函数关闭`popen()`返回的文件描述符,这会迫使子进程退出,然后你可以从`errno`全局变量中获取错误码,如果值为`ECHILD`,说明之前的是子进程的句柄,此时可以用`waitpid(-1, &status, WIFEXITED(status))`获取子进程的PID。 2. **找到子进程**: - 可以通过遍历 `/proc/PID_of_subprocess/stat` 文件,从中提取出进程名称。在这个文件里,`comm`字段包含了进程名。 3. **终止进程**: - 如果找到了目标进程,使用`kill()`函数传入PID和信号(如SIGTERM),尝试优雅地停止进程。对于某些无法正常结束的任务,也可以考虑使用更强烈的信号,比如SIGKILL。 4. **处理异常**: - 需要注意的是,上述操作可能会失败,例如由于权限问题或进程已经终止。确保对可能出现的错误情况进行适当的错误处理。 下面是一个简化的示例代码片段,注意这只是一个基础版本,实际应用中还需要添加更多的错误检查和日志记录: ```c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> #include <fcntl.h> #include <string.h> #define MAX_LINE_LENGTH 1024 int main(int argc, char* argv[]) { FILE* popen_fd = popen("ls", "r"); if (popen_fd == NULL) { perror("Error opening pipe"); return 1; } int pid = -1; // Assuming you've already waited for the child to exit if (WIFEXITED(errno)) { pid = errno; // ECHILD is a special case when the process has terminated } else { pid = waitpid(-1, NULL, WNOHANG); if (pid < 0 && errno != ECHILD) { perror("Error retrieving PID"); return 1; } } if (pid > 0) { // Now you can terminate or kill the process kill(pid, SIGTERM); // Replace with SIGKILL if necessary printf("Terminated process with PID %d\n", pid); } else { // Process not found printf("Process not running\n"); } pclose(popen_fd); return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

高晓伟_Steven

相逢即是有缘,动力源于金钱。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值