linux c 根据程序名获取进程号

复制代码
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <dirent.h>
#include <stdlib.h>
#include <limits.h>

int main(void)
{

    DIR *dir;
    struct dirent *d;
    int pid,i=0;
    char* s;
    dir=opendir("/proc");
    while((d=readdir(dir))!=NULL)
    {
        char exe[PATH_MAX+1];
        char path[PATH_MAX+1];
        int len;
        if((pid=atoi(d->d_name))==0)
        {
            continue;
        }
        snprintf(exe,sizeof(exe),"/proc/%s/exe",d->d_name);
        if((len=readlink(exe,path,PATH_MAX))<0)
        {
            continue;
        }
        path[len]='\0';
        s=strrchr(path,'/');
       // printf("%s %s %s\n",exe,s,path);
        s++;
        //printf("%s\n",s);

        if(!strncmp("tiwangtest",s,strlen("tiwangtest")))
        {
            if(s[strlen("tiwangtest")]==' '||s[strlen("tiwangtest")]=='\0')
            {
                closedir(dir);
                printf("%d\n",pid);
            }
        }
        //sleep(1);
    }
    while(1)
    {}
    return 0;
}
复制代码

 

 在终端使用ps -a命令查看

 

posted @   Wangtn  阅读(517)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
点击右上角即可分享
微信分享提示