我是 OpenBSD 的新手。我以前在 Linux 上工作过。我正在寻找可以找到有关当前正在运行的进程的信息的目录。在 Linux 中,我们有 /proc 目录,其中存在整个列表。但我在 OpenBSD 4.6 中找不到类似的设置。我知道有像 ps、top 和 sysctl 这样的命令,但我想通过 C 代码获取这些信息。
问问题
2271 次
2 回答
2
BSD 中的 procfs 要么被弃用,要么被完全删除,抱歉。话虽如此,将系统的源代码放在 /usr/src 下也很常见,因此如果您确实需要,可以查看它们。或者您可以在网上浏览它们,例如http://bxr.su/o/bin/ps/ps.c
于 2013-12-09T15:33:38.597 回答
0
您可以使用 sysctl 在 kinfo_proc 结构数组中获取正在运行的进程,此类型定义在:
/usr/include/sys/sysctl.h
顶部命令使用一个名为 getprocs 的函数,它以这种方式工作,它定义在:
/usr/src/usr.bin/top/machine.c
下一个实用程序使用稍加修改的 getprocs 版本输出所有正在运行的进程的信息:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <kvm.h>
#include <sys/sysctl.h>
#define TRUE 1
#define FALSE 0
struct kinfo_proc * getprocs( int * count, int threads )
{
struct kinfo_proc * procbase = NULL ;
unsigned int maxslp ;
size_t size = sizeof( maxslp ) ;
int maxslp_mib[] = { CTL_VM, VM_MAXSLP } ;
int mib[6] =
{
CTL_KERN,
KERN_PROC,
threads ? KERN_PROC_KTHREAD | KERN_PROC_SHOW_THREADS : KERN_PROC_KTHREAD,
0,
sizeof( struct kinfo_proc ),
0
} ;
if( sysctl( maxslp_mib, 2, &maxslp, &size, NULL, 0 ) == -1 )
{
perror( "list" ) ;
return NULL ;
}
retry:
if( sysctl( mib, 6, NULL, &size, NULL, 0 ) == -1 )
{
perror( "list" ) ;
return NULL ;
}
size = 5 * size / 4 ; /* extra slop */
procbase = (struct kinfo_proc *)malloc( size ) ;
if( procbase == NULL )
{
perror( "list" ) ;
return NULL ;
}
mib[5] = (int)( size / sizeof( struct kinfo_proc ) ) ;
if( sysctl( mib, 6, procbase, &size, NULL, 0 ) )
{
if( errno == ENOMEM )
{
free( procbase ) ;
goto retry;
}
perror( "list" ) ;
return NULL ;
}
*count = (int)( size / sizeof( struct kinfo_proc ) ) ;
return procbase ;
}
int showinfo( int threads )
{
struct kinfo_proc * list, * proc ;
int count, i ;
if( ( list = getprocs( &count, threads ) ) == NULL )
{
return 1 ;
}
proc = list ;
if( threads )
{
for( i = 0 ; i < count ; ++i, ++proc )
{
if( proc->p_tid != -1 )
{
printf( "%s: pid: %d (tid: %d)\n", proc->p_comm, proc->p_pid, proc->p_tid ) ;
}
}
}
else
{
for( i = 0 ; i < count ; ++i, ++proc )
{
printf( "%s: pid: %d\n", proc->p_comm, proc->p_pid ) ;
}
}
return 0 ;
}
int main( int argc, char * argv[] )
{
if( argc == 1 )
{
return showinfo( FALSE ) ;
}
else if( argc == 2 && ( !strcmp( argv[1], "-t" ) || !strcmp( argv[1], "--threads" ) ) )
{
return showinfo( TRUE ) ;
}
else
{
printf( "Usage:\n" ) ;
printf( " list [-h] [-t]\n\n" ) ;
printf( "Options:\n" ) ;
printf( " -h, --help Print this information\n" ) ;
printf( " -t, --threads Show threads\n\n" ) ;
return 0 ;
}
}
于 2016-07-09T01:29:26.397 回答