当前位置: 技术问答>linux和unix
为什么以下代码不能调用find_task_by_id
来源: 互联网 发布时间:2016-02-07
本文导语: #include #include #include void execname() { struct task_struct *my; my = find_task_by_id(getpid()); printf("%s",my->comm); } int main() { execname(); return 0; } | find_task_by_id 是个内核函数,你在用户空间没法调...
#include
#include
#include
void execname() {
struct task_struct *my;
my = find_task_by_id(getpid());
printf("%s",my->comm);
}
int main() {
execname();
return 0;
}
#include
#include
void execname() {
struct task_struct *my;
my = find_task_by_id(getpid());
printf("%s",my->comm);
}
int main() {
execname();
return 0;
}
|
find_task_by_id
是个内核函数,你在用户空间没法调用.你不能这样直接使用它.
下边是别人写的,可以看看
#include
#include
#include
#include
#include
MODULE_LICENSE("GPL");
MODULE_AUTHOR("scutan");
static int find_read(char *buffer, char **buffer_location, off_t offset, int count, int *eof, void *data)
{
struct task_struct *p;
int pid;
pid = current->pid;
p = find_task_by_pid(pid);
sprintf(buffer, "%dt%sn", p->pid, p->comm);
return strlen(buffer);
}
static int __init find_init(void)
{
struct proc_dir_entry *entry;
entry = create_proc_entry("findpid", 0644, NULL);
if (entry == 0)
{
printk(KERN_ERR "creat_proc_entry failedn");
return -1;
}
entry->mode = S_IFREG | S_IRUGO;
entry->size = 100;
entry->owner = THIS_MODULE;
entry->uid = 0;
entry->gid = 0;
entry->read_proc = find_read;
return 0;
}
void __exit find_exit(void)
{
remove_proc_entry("findpid", &proc_root);
}
module_init(find_init);
module_exit(find_exit);
Makefile
代码:
obj-m:=find.o
KERNELDIR:=/usr/src/linux
default:
make -C $(KERNELDIR) M=$(shell pwd) modules
install:
insmod find.ko
uninstall:
rmmod find.ko
clean:
rm -rf *.o *.mod.c *.ko
另外还有一个测试程序get.c
代码:
#include
#include
#include
#include
#include
int main()
{
int fd;
char buf[50];
fd = open("/proc/findpid", O_RDONLY);
if (fd
是个内核函数,你在用户空间没法调用.你不能这样直接使用它.
下边是别人写的,可以看看
#include
#include
#include
#include
#include
MODULE_LICENSE("GPL");
MODULE_AUTHOR("scutan");
static int find_read(char *buffer, char **buffer_location, off_t offset, int count, int *eof, void *data)
{
struct task_struct *p;
int pid;
pid = current->pid;
p = find_task_by_pid(pid);
sprintf(buffer, "%dt%sn", p->pid, p->comm);
return strlen(buffer);
}
static int __init find_init(void)
{
struct proc_dir_entry *entry;
entry = create_proc_entry("findpid", 0644, NULL);
if (entry == 0)
{
printk(KERN_ERR "creat_proc_entry failedn");
return -1;
}
entry->mode = S_IFREG | S_IRUGO;
entry->size = 100;
entry->owner = THIS_MODULE;
entry->uid = 0;
entry->gid = 0;
entry->read_proc = find_read;
return 0;
}
void __exit find_exit(void)
{
remove_proc_entry("findpid", &proc_root);
}
module_init(find_init);
module_exit(find_exit);
Makefile
代码:
obj-m:=find.o
KERNELDIR:=/usr/src/linux
default:
make -C $(KERNELDIR) M=$(shell pwd) modules
install:
insmod find.ko
uninstall:
rmmod find.ko
clean:
rm -rf *.o *.mod.c *.ko
另外还有一个测试程序get.c
代码:
#include
#include
#include
#include
#include
int main()
{
int fd;
char buf[50];
fd = open("/proc/findpid", O_RDONLY);
if (fd