Ubuntu 编写系统调用以返回进程的pid

Ubuntu 编写系统调用以返回进程的pid,ubuntu,linux-kernel,system-calls,Ubuntu,Linux Kernel,System Calls,我正在编写一个系统调用,在提供进程名称时返回进程的pid。找到值后返回pid,否则返回-1 我按照所有步骤编写系统调用: 在syscall表中添加syscall,在syscalls.h中添加syscall,更改了linux/Makefile,创建了一个名为pname的目录。一切顺利,一切都完成了。这是我的pname.c #include <linux/syscalls.h> #include <linux/kernel.h> #include <linux/sche

我正在编写一个系统调用,在提供进程名称时返回进程的pid。找到值后返回pid,否则返回-1

我按照所有步骤编写系统调用: 在syscall表中添加syscall,在syscalls.h中添加syscall,更改了linux/Makefile,创建了一个名为pname的目录。一切顺利,一切都完成了。这是我的pname.c

#include <linux/syscalls.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/tty.h>
#include <linux/string.h>
#include "pname.h"
asmlinkage int pnametoid(char* name){

 struct task_struct *task;

 struct tty_struct *my_tty;

 my_tty = get_current_tty();

 for_each_process(task){

 if(strcmp(task->comm, name) == 0)
    return task->pid;
 }
 return -1;
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括“pname.h”
ASMLINKING int pnametoid(字符*名称){
结构任务\u结构*任务;
struct tty_struct*my\u tty;
my_tty=获取当前_tty();
对于每个流程(任务){
if(strcmp(任务->通信,名称)==0)
返回任务->pid;
}
返回-1;
}
这是我的测试程序test.c

#include <stdio.h>
#include <linux/kernel.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <string.h>
int main(){
 char name[32];
 puts("Enter process to find");
 scanf("%s",name);
 strtok(name, "\n");
 int status = syscall(317, name); //syscall number 317 and passing in the 
string. 
printf("System call returned %d\n", status);
return 0;
}
#包括
#包括
#包括
#包括
#包括
int main(){
字符名[32];
puts(“输入流程以查找”);
scanf(“%s”,名称);
strtok(名称“\n”);
int status=syscall(317,name);//syscall编号317并传入
一串
printf(“系统调用返回%d\n”,状态);
返回0;
}

我尝试输入进程名,如“test”或“sshd”,但返回值总是-1,而不是pid。我做错了什么?

在strtok和syscall函数中使用名称之前,您是否尝试过打印名称?看看你是否得到了你想要的字符串typed@josemartindev嘿,我试过你说的话,是的,字符串是我键入的,在
printk()
中为每个进程
输入
task->comm
name
,以确保准确比较想要比较的内容。然后在
dmesg
中检查这个的输出。如果直接将
pnametoid
插入syscalls表,我怀疑
char*name
中的
pnametoid
没有指向最近内核中传递到系统调用的字符串。产生这种怀疑的原因是,在最近的内核中,在syscall函数周围使用了一个额外的包装器,请参见我的回答:-可能您的
char*name
实际上包含一个指向
struct pt_regs
的指针,而不是指向调用进程传递的字符串的指针。您可能希望看到getpid()系统调用实现。请参见此处:在strtok和syscall函数中使用名称之前,您是否尝试过打印名称?看看你是否得到了你想要的字符串typed@josemartindev嘿,我试过你说的话,是的,字符串是我键入的,在
printk()
中为每个进程
输入
task->comm
name
,以确保准确比较想要比较的内容。然后在
dmesg
中检查这个的输出。如果直接将
pnametoid
插入syscalls表,我怀疑
char*name
中的
pnametoid
没有指向最近内核中传递到系统调用的字符串。产生这种怀疑的原因是,在最近的内核中,在syscall函数周围使用了一个额外的包装器,请参见我的回答:-可能您的
char*name
实际上包含一个指向
struct pt_regs
的指针,而不是指向调用进程传递的字符串的指针。您可能希望看到getpid()系统调用实现。请看这里: