실행 중인 프로세스를 나열하는 Linux API?
Linux 시스템에서 실행 중인 프로세스를 나열하고 각 프로세스가 열려 있는 파일을 나열할 수 있는 C/C++ API가 필요합니다.
저는 /proc/ 파일 시스템을 직접 읽고 싶지 않습니다.
이걸 할 방법을 생각해 낼 수 있는 사람?
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에 링크하는 것입니다.이 API는 repo(또는 이미 설치되어 있는 경우)에서 사용할 수 있어야 하지만 헤더에 대한 "dev" 변형이 필요합니다.
행운을 빌어요
'/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.Once에 있는 제 기사에서 따온 것입니다.자신의 시스템 콜이 있습니다.사용자 공간 프로그램에서 호출할 수 있습니다.
여기 있습니다(C/C++):
http://ubuntuforums.org/showthread.php?t=657097 에서 찾을 수 있습니다.
기본적으로, 이 기능은 모든 숫자 폴더를 루프하는 것입니다./proc/<pid>
그 후, 에 대한 readlink를 참조해 주세요./proc/<pid>/exe
또는 명령줄에서 명령어를 사용할 경우cat /proc/<pid>/cmdline
프로세스에 의해 열려 있는 파일 설명자는 다음과 같습니다./proc/<pid>/fd/<descriptor>
파일명은 각 심볼링크에서 readlink를 실행하여 얻을 수 있습니다.readlink /proc/<pid>/fd/<descriptor>
.fd는 /dev/socket, 소켓, 파일 등의 디바이스일 수 있습니다.또한 그 이상일 수도 있습니다.
#nothers < unistd.h>
ssize_t readlink (const char *path, char *buf, size_t bufsiz);
성공하면 readlink()는 buf에 배치된 바이트 수를 반환합니다.
오류가 발생하면 -1이 반환되고 오류를 나타내도록 errno가 설정됩니다.
그나저나 이것은 같은 것이다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 ;
}
PS 및 기타 모든 툴(커널 모듈 제외)은 에서 읽어낸 것입니다./proc
/proc
는 사용자 모드프로세스가 커널에서만 사용할 수 있는 데이터를 읽을 수 있도록 커널에 의해 즉시 작성된 특수한 파일 시스템입니다.
은 '읽다'에서 입니다./proc
.
직관적으로 볼 수 ./proc
파일 시스템의 구조를 확인합니다.에는 「」가 ./proc/pid
아이디 '피드'입니다.이 폴더 안에는 현재 프로세스에 대한 다른 데이터를 포함하는 여러 파일이 있습니다. 시 ★★★
strace ps -aux
은 이 프로그램이 진행되는지 될 것입니다.ps
/proc
.
/proc를 읽지 않고 이를 실행하는 유일한 방법은 "ps aux"를 호출하고 모든 행을 통과하여 두 번째 열(PID)을 읽고 lsof -p [PID]를 호출하는 것입니다.
... /proc ;를 읽을 것을 권장합니다.)
그렇게 하지 않으면 어떤 API를 사용하든 결국 /proc 파일 시스템을 읽게 될 것입니다.다음은 이를 수행하는 프로그램의 예입니다.
하지만 안타깝게도 API는 아닙니다.
모든 프로세스의 pid를 이름으로 쉽게 fin할 수 있는 방법
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);
}
proc를 읽는 것도 나쁘지 않다.C++에서는 표시할 수 없지만 다음 D코드가 올바른 방향을 알려줄 것입니다.
std.stdio Import;std.string Import;import std.파일링import std.regexp;std.c.linux.linux Import; 에일리어스 std.string.breakd; string srex = "^/context/[0-9]+$";string trex = "상태:[ \t ][SR],RegExplex;RegExp rext; string [ ]scanPidDirs(문자열 타깃){string[] 결과; 부울콜백(DirEntry*de){(de.isdir)의 경우{if(rex.find(de.name) > = 0){문자열 [] a = 폭발(de.name, "/");문자열 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 ~ "/subline"); // 이것은 null로 종료되었습니다.if (x.length) x.length = x.length-1;a = 폭발(x, "/");(a.length)의 경우x = a[a.length-1]; 또 다른x = " ,if (x == target){결과 ~= pid ~ "/" ~x;}}}}true를 반환한다.} listdirc/callback", &callback); return result.syslog; } 보이드 메인(string[] args){rex= new RegExp(srex); rext= new RegExp(trex); 문자열 [] a = scanPidDirs(args[1]);(!a.length)의 경우{writefln("찾을 수 없습니다"); 반품}writefln"%d 매칭 프로세스", a.length); 포어치(a)를 앞지르다{문자열 [] p = 폭발(s, "/");int pid = atoi(p[0]);writef("Stop %s (%d)"? ", s, pid; 문자열 r = readln();if (r == "Y\n" | r == "y\n")kill(pid, SIGUSR1);}}
libprocps
할 수 있습니다.Ubuntu 13.04에서는strace ps
그러면 볼 수 요.ps
libprocps
.
언급URL : https://stackoverflow.com/questions/939778/linux-api-to-list-running-processes
'sourcecode' 카테고리의 다른 글
##(더블 해시)는 프리프로세서 디렉티브에서 무엇을 합니까? (0) | 2022.08.30 |
---|---|
PTHREAD_MUTEX_INITIALIZER vs pthread_mutex_init (&mutex, param) (0) | 2022.08.30 |
Vue.js를 사용하여 클릭 시 특정 하위 요소를 업데이트하려면 어떻게 해야 합니까? (0) | 2022.08.30 |
오류: Java 가상 시스템 Mac OSX Mavericks를 생성할 수 없습니다. (0) | 2022.08.30 |
printf의 %s 지정자를 사용하여 NULL을 인쇄하는 동작은 무엇입니까? (0) | 2022.08.30 |