Linux API列出正在运行的进程?

时间:2009-06-02 14:06:39

标签: c++ c linux api process

我需要一个C / C ++ API,允许我在Linux系统上列出正在运行的进程,并列出每个进程打开的文件。

希望最终直接读取/ proc / file系统。

有人可以想办法吗?

9 个答案:

答案 0 :(得分:40)

http://procps.sourceforge.net/

http://procps.cvs.sourceforge.net/viewvc/procps/procps/proc/readproc.c?view=markup

是ps和其他处理工具的来源。他们确实使用proc(表明它可能是传统和最好的方式)。它们的来源非常易读。文件

/procps-3.2.8/proc/readproc.c

可能有用。另外一个有用的建议是由ephemient发布链接到 libproc 提供的API,这应该在您的仓库中提供(或者我已经安装了)但是您需要标题的“-dev”变体和什么不是。

祝你好运

答案 1 :(得分:23)

如果您不想阅读'/ proc。然后你可以考虑编写一个内核模块,它将实现你自己的系统调用。并且应该编写系统调用,以便它可以获取当前进程的列表,例如:

/* ProcessList.c 
    Robert Love Chapter 3
    */
    #include < linux/kernel.h >
    #include < linux/sched.h >
    #include < linux/module.h >

    int init_module(void)
    {
    struct task_struct *task;
    for_each_process(task)
    {
    printk("%s [%d]\n",task->comm , task->pid);
    }

    return 0;
    }

    void cleanup_module(void)
    {
    printk(KERN_INFO "Cleaning Up.\n");
    }

上面的代码来自我在http://linuxgazette.net/133/saha.html的文章。一旦有了自己的系统调用,就可以通过用户空间程序调用它。

答案 2 :(得分:8)

如果你不这样做,那么我猜你将使用的API将最终读取/ proc文件系统。以下是程序执行此操作的一些示例:

但不幸的是,这并不构成API。

答案 3 :(得分:7)

你去(C / C ++):

你可以在这里找到它: http://ubuntuforums.org/showthread.php?t=657097

基本上,它的作用是循环遍历/ proc /中的所有数字文件夹,然后它在/ proc // exe上执行readlink,或者如果你想要命令行参数cat / proc // cmdline

顺便说一句,这与readproc.c做(或至少做过)的方式相同 当然,希望他们没有缓冲区溢出可能性。

#ifndef __cplusplus
    #define _GNU_SOURCE
#endif

#include <unistd.h>
#include <dirent.h>
#include <sys/types.h> // for opendir(), readdir(), closedir()
#include <sys/stat.h> // for stat()

#ifdef __cplusplus
    #include <iostream>
    #include <cstdlib>
    #include <cstring>
    #include <cstdarg>
#else
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <stdarg.h>
#endif


#define PROC_DIRECTORY "/proc/"
#define CASE_SENSITIVE    1
#define CASE_INSENSITIVE  0
#define EXACT_MATCH       1
#define INEXACT_MATCH     0


int IsNumeric(const char* ccharptr_CharacterList)
{
    for ( ; *ccharptr_CharacterList; ccharptr_CharacterList++)
        if (*ccharptr_CharacterList < '0' || *ccharptr_CharacterList > '9')
            return 0; // false
    return 1; // true
}


int strcmp_Wrapper(const char *s1, const char *s2, int intCaseSensitive)
{
    if (intCaseSensitive)
        return !strcmp(s1, s2);
    else
        return !strcasecmp(s1, s2);
}

int strstr_Wrapper(const char* haystack, const char* needle, int intCaseSensitive)
{
    if (intCaseSensitive)
        return (int) strstr(haystack, needle);
    else
        return (int) strcasestr(haystack, needle);
}


#ifdef __cplusplus
pid_t GetPIDbyName(const char* cchrptr_ProcessName, int intCaseSensitiveness, int intExactMatch)
#else
pid_t GetPIDbyName_implements(const char* cchrptr_ProcessName, int intCaseSensitiveness, int intExactMatch)
#endif
{
    char chrarry_CommandLinePath[100]  ;
    char chrarry_NameOfProcess[300]  ;
    char* chrptr_StringToCompare = NULL ;
    pid_t pid_ProcessIdentifier = (pid_t) -1 ;
    struct dirent* de_DirEntity = NULL ;
    DIR* dir_proc = NULL ;

    int (*CompareFunction) (const char*, const char*, int) ;

    if (intExactMatch)
        CompareFunction = &strcmp_Wrapper;
    else
        CompareFunction = &strstr_Wrapper;


    dir_proc = opendir(PROC_DIRECTORY) ;
    if (dir_proc == NULL)
    {
        perror("Couldn't open the " PROC_DIRECTORY " directory") ;
        return (pid_t) -2 ;
    }

    // Loop while not NULL
    while ( (de_DirEntity = readdir(dir_proc)) )
    {
        if (de_DirEntity->d_type == DT_DIR)
        {
            if (IsNumeric(de_DirEntity->d_name))
            {
                strcpy(chrarry_CommandLinePath, PROC_DIRECTORY) ;
                strcat(chrarry_CommandLinePath, de_DirEntity->d_name) ;
                strcat(chrarry_CommandLinePath, "/cmdline") ;
                FILE* fd_CmdLineFile = fopen (chrarry_CommandLinePath, "rt") ;  // open the file for reading text
                if (fd_CmdLineFile)
                {
                    fscanf(fd_CmdLineFile, "%s", chrarry_NameOfProcess) ; // read from /proc/<NR>/cmdline
                    fclose(fd_CmdLineFile);  // close the file prior to exiting the routine

                    if (strrchr(chrarry_NameOfProcess, '/'))
                        chrptr_StringToCompare = strrchr(chrarry_NameOfProcess, '/') +1 ;
                    else
                        chrptr_StringToCompare = chrarry_NameOfProcess ;

                    //printf("Process name: %s\n", chrarry_NameOfProcess);
                    //printf("Pure Process name: %s\n", chrptr_StringToCompare );

                    if ( CompareFunction(chrptr_StringToCompare, cchrptr_ProcessName, intCaseSensitiveness) )
                    {
                        pid_ProcessIdentifier = (pid_t) atoi(de_DirEntity->d_name) ;
                        closedir(dir_proc) ;
                        return pid_ProcessIdentifier ;
                    }
                }
            }
        }
    }
    closedir(dir_proc) ;
    return pid_ProcessIdentifier ;
}

#ifdef __cplusplus
    pid_t GetPIDbyName(const char* cchrptr_ProcessName)
    {
        return GetPIDbyName(cchrptr_ProcessName, CASE_INSENSITIVE, EXACT_MATCH) ;
    }
#else
    // C cannot overload functions - fixed
    pid_t GetPIDbyName_Wrapper(const char* cchrptr_ProcessName, ... )
    {
        int intTempArgument ;
        int intInputArguments[2] ;
        // intInputArguments[0] = 0 ;
        // intInputArguments[1] = 0 ;
        memset(intInputArguments, 0, sizeof(intInputArguments) ) ;
        int intInputIndex ;
        va_list argptr;

        va_start( argptr, cchrptr_ProcessName );
            for (intInputIndex = 0;  (intTempArgument = va_arg( argptr, int )) != 15; ++intInputIndex)
            {
                intInputArguments[intInputIndex] = intTempArgument ;
            }
        va_end( argptr );
        return GetPIDbyName_implements(cchrptr_ProcessName, intInputArguments[0], intInputArguments[1]);
    }

    #define GetPIDbyName(ProcessName,...) GetPIDbyName_Wrapper(ProcessName, ##__VA_ARGS__, (int) 15)

#endif

int main()
{
    pid_t pid = GetPIDbyName("bash") ; // If -1 = not found, if -2 = proc fs access error
    printf("PID %d\n", pid);
    return EXIT_SUCCESS ;
}

答案 4 :(得分:5)

PS和其他所有工具(内核模块除外)都从/proc读取。 /proc是内核动态创建的特殊文件系统,因此用户模式进程可以读取原本只能用于内核的数据。

因此,建议的方法是阅读/proc

您可以快速直观地查看/proc文件系统,了解其结构。 对于每个进程,都有一个/proc/pid,其中pid是进程ID号。在此文件夹中,有几个文件包含有关当前进程的不同数据。 如果你运行

strace ps -aux

您将看到程序ps如何从/proc读取此数据。

答案 5 :(得分:3)

没有读取/ proc的唯一方法是调用“ps aux”,遍历每一行,读取第二列(PID)并用它调用lsof -p [PID]。

......我建议阅读/ proc;)

答案 6 :(得分:3)

来自procps-ng project的图书馆libprocps。在Ubuntu 13.04上,如果您strace ps,则可以看到ps使用libprocps

答案 7 :(得分:2)

阅读过程并不算太糟糕。我无法用C ++向您展示,但以下D代码应指向正确的方向:

import std.stdio;
import std.string;
import std.file;
import std.regexp;
import std.c.linux.linux;

alias std.string.split explode;

string srex = "^/proc/[0-9]+$";
string trex = "State:[ \t][SR]";
RegExp rex;
RegExp rext;

   string[] scanPidDirs(string target)
   {
      string[] result;

      bool callback(DirEntry* de)
      {
         if (de.isdir)
         {
            if (rex.find(de.name) >= 0)
            {
                string[] a = explode(de.name, "/");
                string pid = a[a.length-1];
                string x = cast(string) std.file.read(de.name ~ "/status");
                int n = rext.find(x);
                if  (n >= 0)
                {
                    x = cast(string) std.file.read(de.name ~ "/cmdline");
                    // This is null terminated
                    if (x.length) x.length = x.length-1;
                    a = explode(x, "/");
                    if (a.length)
                       x = a[a.length-1];
                    else
                       x = "";
                     if  (x == target)
                    {
                        result ~= pid ~ "/" ~x;
                    }
                }
             }
          }
          return true;
      }

      listdir("/proc", &callback);
      return result.dup;
   }

void main(string[] args)
{
    rex= new RegExp(srex);
    rext= new RegExp(trex);
    string[] a = scanPidDirs(args[1]);
    if (!a.length)
    {
        writefln("Not found");
        return;
    }
    writefln("%d matching processes", a.length);
    foreach (s; a)
    {
       string[] p = explode(s, "/");
       int pid = atoi(p[0]);
       writef("Stop %s (%d)? ", s, pid);
       string r = readln();
       if (r == "Y\n" || r == "y\n")
          kill(pid, SIGUSR1);
    }
}

答案 8 :(得分:0)

通过名称

轻松完成任何流程的pid
pid_t GetPIDbyName(char* ps_name)
{

    FILE *fp;
    char *cmd=(char*)calloc(1,200);
    sprintf(cmd,"pidof %s",ps_name);
    fp=popen(cmd,"r");
    fread(cmd,1,200,fp);
    fclose(fp);
    return atoi(cmd);
}