这篇文章几乎回答了我的问题: Linux API to list running processes?
但是示例代码(C ++ / C - 见下文)中缺少的是该过程的参数。例如,名为mypaint的程序将仅列为“python2.7”而不是完整的可执行文件和参数“python2.7 / usr / bin / mypaint”。
来自proc的手册页: 的/ proc / [PID] / CMDLINE 这包含进程的完整命令行,除非进程是僵尸。在后一种情况下,此文件中没有任何内容:也就是说,对此文件的读取将返回0个字符。命令行参数在此文件中显示为由空字节('\ 0')分隔的一组字符串,在最后一个字符串后面还有一个空字节。
如何修改此代码以列出流程的参数?
#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 ;
}
(chrarry_NameOfProcess =只能执行如何显示参数)?
答案 0 :(得分:4)
假设你真的不想单独解析每个参数,而只是想像你现在一样打印它们,一个简单的方法是:
(1)将fread
替换为fscanf
并读取一些任意大量的字节。 (或者首先找到文件长度,如果你想专业地读取数量,那么这将读取。)这将读取包括空字节在内的所有内容。
(2)循环缓冲区,用空格替换空值。
(3)在读取的字节末尾放置一个null以终止字符串。
(4)然后打印出来。
所以在你的GetPIDbyName()函数中就像:
const int BUFFERSIZE = 300;
int bytesread;
char chrarry_NameOfProcess[BUFFERSIZE] ;
//...........
FILE* fd_CmdLineFile = fopen (chrarry_CommandLinePath, "rb") ;
if (fd_CmdLineFile)
{
//fscanf(fd_CmdLineFile, "%s", chrarry_NameOfProcess) ;
bytesread = fread(chrarry_NameOfProcess, 1, BUFFERSIZE, fd_CmdLineFile);
for (int i = 0; i < bytesread; ++i)
if (chrarry_NameOfProcess[i] == '\0')
chrarry_NameOfProcess[i] = ' ';
chrarry_NameOfProcess[bytesread] = '\0';
fclose(fd_CmdLineFile);
//... the rest
}
答案 1 :(得分:2)
要读取以NULL结尾的字符串,您将不得不做一些诡计。
如果你像fgets(buffer, size, fp)
那样打电话并尝试打印结果,那么你就不会得到你想要的东西。原因是当您使用printf()
尝试打印结果时,您将获得第一个以NULL结尾的字符串。打印完之后,需要转到下一个以NULL结尾的字符串,因为NULL表示字符串的结尾。
所以,有些代码可以做到这一点:
int len = 0;
while((len = read(fd, buffer, sizeof(buffer))) > 0) {
/* NOTE: not sure if this condition is correct: might be -1. */
if(len == sizeof(buffer)) { /* arguments too long for buffer, use what exists or print error message. */ }
int i = 0;
while(i < len) {
char *s = buffer + i;
printf("Argument: %s\n", s);
i += strlen(s) + 1; /* +1 skips over NULL at end of string. */
}
}
有点澄清:buffer + i
相当于&buffer[i]
。它基本上将缓冲区视为包含多个以NULL结尾的字符串链接在一起的字符数组。
我在这里使用read()
而不是fgets()
的原因是,当使用fgets()
时,更难以确定从文件中真正读取了多少字节。 strlen()
没有帮助,我知道的唯一方法是检查换行符的位置,该换行符假定首先存在换行符。 。 。这太丑了。
编辑:或者你可以使用ftell(),我想,但这甚至更加丑陋!