21xrx.com
2025-03-29 11:25:28 Saturday
文章检索 我的文章 写文章
如何在C语言中查看运行进程
2023-06-15 18:13:12 深夜i     11     0

在开发一个系统级软件或者进程监控工具的时候,了解正在运行的进程是非常重要的。而在C语言中,我们可以通过一些底层API来实现进程查看的功能。

在Linux操作系统中,我们可以使用sys/types.h和dirent.h这两个头文件来实现进程查看功能。通过读取/proc目录下的进程信息,我们就可以获取正在运行的进程信息。具体的实现方式可以参考下面的示例代码:

#include 
#include 
#include 
#include 
int main()
{
  DIR* dir;
  struct dirent* dir_info;
  FILE* fd;
  char path[1024];
  dir = opendir("/proc");
  if (dir)
  {
    while ((dir_info = readdir(dir)) != NULL)
    {
      if (dir_info->d_type == DT_DIR)
      {
        if (isdigit(dir_info->d_name[0]))
        {
          strncpy(path, "/proc/", sizeof(path));
          strncat(path, dir_info->d_name, sizeof(path));
          /* Get process name */
          strncat(path, "/comm", sizeof(path));
          fd = fopen(path, "r");
          fscanf(fd, "%s", path);
          printf("Process name: %s\n", path);
          fclose(fd);
          /* Get process ID */
          printf("Process ID: %s\n", dir_info->d_name);
        }
      }
    }
    closedir(dir);
  }
  return 0;
}

上面的代码中,我们首先打开/proc目录,在里面遍历所有的进程目录,然后读取每个进程目录下的comm文件,获取进程的名称,再读取当前目录名,即可获取进程ID。

通过上面的示例代码,我们就可以在C语言中实现进程查看的功能了。同时,我们还可以生成一些关键词,如C语言、进程、查看、运行、sys/types.h、dirent.h、/proc目录等。

  
  

评论区

请求出错了