Linux驱动获取进程PID和进程名字

来源:互联网 发布:北京学唱歌 知乎 编辑:程序博客网 时间:2024/06/05 15:27

Linux驱动打印进程PID和进程名字

在内核中, 进程用task_struct结构表示, 其中有char comm[TASK_COMM_LEN]成员, 其含义是

executable name excluding path

按照标准做法, 应该使用get_task_comm()/set_task_comm()函数来获取/设置此成员(为避免竞争, 这俩函数会调用task_lock()先拿锁).
我们这里简便起见,就直接获取comm值了,如下:

printk("%s (pid=%d, comm=%s)\n", __func__, current->pid, current->comm);

扩展阅读:

// task_struct的基本信息struct task_struct {//这个是进程的运行时状态,-1代表不可运行,0代表可运行,>0代表已停止。 volatile long state; /*flags是进程当前的状态标志,具体的如:0x00000002表示进程正在被创建;0x00000004表示进程正准备退出;0x00000040 表示此进程被fork出,但是并没有执行exec;0x00000400表示此进程由于其他进程发送相关信号而被杀死 。*/ unsigned int flags;//表示此进程的运行优先级 unsigned int rt_priority;//这里出现了list_head结构体,详情请参考 struct list_head tasks;//这里出现了mm_struct 结构体,该结构体记录了进程内存使用的相关情况,详情请参考 struct mm_struct *mm;/* 接下来是进程的一些状态参数*/ int exit_state; int exit_code, exit_signal;//这个是进程号 pid_t pid;//这个是进程组号 pid_t tgid;//real_parent是该进程的”亲生父亲“,不管其是否被“寄养”。 struct task_struct *real_parent;//parent是该进程现在的父进程,有可能是”继父“ struct task_struct *parent;//这里children指的是该进程孩子的链表,可以得到所有孩子的进程描述符,但是需使用list_for_each和list_entry,list_entry其实直接使用了container_of,详情请参考 struct list_head children;//同理,sibling该进程兄弟的链表,也就是其父亲的所有孩子的链表。用法与children相似。 struct list_head sibling;//这个是主线程的进程描述符,也许你会奇怪,为什么线程用进程描述符表示,因为linux并没有单独实现线程的相关结构体,只是用一个进程来代替线程,然后对其做一些特殊的处理。 struct task_struct *group_leader;//这个是该进程所有线程的链表。 struct list_head thread_group;//顾名思义,这个是该进程使用cpu时间的信息,utime是在用户态下执行的时间,stime是在内核态下执行的时间。 cputime_t utime, stime;//下面的是启动的时间,只是时间基准不一样。 struct timespec start_time; struct timespec real_start_time;//comm是保存该进程名字的字符数组,长度最长为15,因为TASK_COMM_LEN为16。 char comm[TASK_COMM_LEN];/* 文件系统信息计数*/ int link_count, total_link_count;/*该进程在特定CPU下的状态*/ struct thread_struct thread;/* 文件系统相关信息结构体*/ struct fs_struct *fs;/* 打开的文件相关信息结构体*/ struct files_struct *files; /* 信号相关信息的句柄*/ struct signal_struct *signal; struct sighand_struct *sighand; /*这些是松弛时间值,用来规定select()和poll()的超时时间,单位是纳秒nanoseconds */ unsigned long timer_slack_ns; unsigned long default_timer_slack_ns;};
阅读全文
0 0