c - 如何使用模块获取进程ID、名称和状态

标签 c linux module linux-device-driver

<分区>

我想使用模块打印进程 ID、进程名称和进程状态,作为测试,我尝试使用 getpid() 函数打印进程 ID,但出现以下错误:

函数'printf'的隐式声明

函数'getpid'的隐式声明

如何解决这些错误以及如何打印进程名称和状态。

#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>

/* This function is called when the module is loaded. */
int simple_init(void)
{
       printk(KERN_INFO "Loading Module\n");
       printf("The process id is %\n", (int) getpid());
       return 0;
}

/* This function is called when the module is removed. */
void simple_exit(void) {
    printk(KERN_INFO "Removing Module\n");
}

/* Macros for registering module entry and exit points. */
module_init( simple_init );
module_exit( simple_exit );

MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Simple Module");
MODULE_AUTHOR("SGG");

最佳答案

#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sched.h> //task_pid_nr

/* This function is called when the module is loaded. */
int simple_init(void)
{
       printk(KERN_INFO "Loading Module\n");
       printk("The process id is %d\n", (int) task_pid_nr(current));
       printk("The process vid is %d\n", (int) task_pid_vnr(current));
       printk("The process name is %s\n", current->comm);
       printk("The process tty is %d\n", current->signal->tty);
       printk("The process group is %d\n", (int) task_tgid_nr(current));
       printk("\n\n");
   //return -1; //debug mode of working
   return 0;
}

/* This function is called when the module is removed. */
void simple_exit(void) {
    printk(KERN_INFO "Removing Module\n");
}

/* Macros for registering module entry and exit points. */
module_init( simple_init );
module_exit( simple_exit );

MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Simple Module");
MODULE_AUTHOR("SGG");

关于c - 如何使用模块获取进程ID、名称和状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26451729/

相关文章:

python - 如何获取 __init__.py 文件中导入的当前模块?

c - 从函数传递一 block 内存

c - 带有数组指针的 union 声明?

linux - 使用 autorid 在多个域的 Linux 客户端之间保持一致的 UID 和 GID

linux - 我应该如何在我的 .htaccess 文件中编写这些重写规则

python - 测试抽象数据类型

c - 程序从字符串(名称)中获取缩写,无法删除所有空格

传递给 `msgpack_pack_int()` 宏的计数器变量不递增

ruby-on-rails - 使用 每当 gem for Rails 在 cron 作业中重复进程

c - Makefile - 包含库