linux c语言查找指定程序pid

工作上需要向特定进程发送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
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

高晓伟_Steven

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

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

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

打赏作者

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

抵扣说明:

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

余额充值