linux c语言查找指定程序pid

来源:互联网 发布:知乎入门级古典音乐 编辑:程序博客网 时间:2024/06/11 05:31

工作上需要向特定进程发送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
原创粉丝点击