LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1409|回复: 5

请教: 从进程名获得进程ID?

[复制链接]
发表于 2004-7-28 11:15:12 | 显示全部楼层 |阅读模式
如果我要向pppd发送一个信号, 我又如何知道pppd的进程ID呢?
在linuxforum上有位仁兄说"遍历了/proc/*/stat, 从里面获得了执行文件的名称. 这种方法的可移植性可能不太好".
那是否有其他方法呢?

谢谢!
发表于 2004-7-28 11:22:18 | 显示全部楼层
ps
 楼主| 发表于 2004-7-28 11:42:09 | 显示全部楼层
在编程中实现?
发表于 2004-7-28 13:31:43 | 显示全部楼层
仅供参考,能实现功能但效率不高

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <assert.h>

  5. int
  6. getpidbyname(const char *name)
  7. {
  8.         char buf[128];
  9.         FILE *fp = tmpfile();

  10.         assert(name);

  11.         /* The buf save a shell command that take pid to tmpfile */
  12.         sprintf(buf, "ps | awk '/.*%s.*/{print $1}' >&%d",
  13.                 name, fileno(fp));

  14.         /* Run the command */
  15.         if (-1 == system(buf))
  16.         {
  17.                 perror("system ERROR");
  18.                 exit(1);
  19.         }

  20.         /* Get pid from tmpfile */
  21.         fseek(fp, 0, SEEK_SET);
  22.         if (NULL == fgets(buf, sizeof buf, fp))
  23.         {
  24.                 perror("fgets-ERROR");
  25.                 exit(1);
  26.         }

  27.         return atoi(buf);
  28. }

  29. int main()
  30. {
  31.         printf("bash pid = %d\n", getpidbyname("bash"));
  32.         return 0;
  33. }
复制代码
发表于 2004-7-28 13:40:33 | 显示全部楼层

  1. sprintf(buf, "ps | awk '/.*%s.*/{print $1}' >&%d",
  2.                 name, fileno(fp));
复制代码

把里面的 ps 改成 ps -A
 楼主| 发表于 2004-7-28 15:28:37 | 显示全部楼层
谢谢
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表