为什么以下代码不能调用find_task_by_id

kes2000 2007-08-26 10:17:03
#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;
}
...全文
109 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
cceczjxy 2007-08-26
  • 打赏
  • 举报
回复
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;
}

23,121

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧