|
发表于 2004-7-28 13:31:43
|
显示全部楼层
仅供参考,能实现功能但效率不高
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <assert.h>
- int
- getpidbyname(const char *name)
- {
- char buf[128];
- FILE *fp = tmpfile();
- assert(name);
- /* The buf save a shell command that take pid to tmpfile */
- sprintf(buf, "ps | awk '/.*%s.*/{print $1}' >&%d",
- name, fileno(fp));
- /* Run the command */
- if (-1 == system(buf))
- {
- perror("system ERROR");
- exit(1);
- }
- /* Get pid from tmpfile */
- fseek(fp, 0, SEEK_SET);
- if (NULL == fgets(buf, sizeof buf, fp))
- {
- perror("fgets-ERROR");
- exit(1);
- }
- return atoi(buf);
- }
- int main()
- {
- printf("bash pid = %d\n", getpidbyname("bash"));
- return 0;
- }
复制代码 |
|