日期:2014-05-16  浏览次数:20625 次

为什么以下代码不能调用find_task_by_id
#include   <stdio.h>
#include   <sys/stat.h>
#include   <stdlib.h>
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 <linux/kernel.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/init.h>
#include <linux/sched.h>

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, "%d\t%s\n ", 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 failed\n ");
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 <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>

int main()
{
int fd;
char buf[50];
fd = open( "/proc/findpid ", O_RDONLY);
if (fd < 0)
{
printf( "error\n ");
exit(1);
}
memset(buf, 0, sizeof(buf));
if (read(fd, buf, 50) < 0)
{
printf( "read error\n ");
exit(1);
}
printf( "buf = %s\n ", buf);
printf( "getpid = %d\n ", getpid());
return 0;
}