首页 > 解决方案 > 编写系统调用返回进程的pid

问题描述

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

我按照所有步骤编写系统调用:在系统调用表中添加系统调用,在 syscalls.h 中添加它,更改 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;
}

这是我的测试程序 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;
}

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

标签: ubuntulinux-kernelsystem-calls

解决方案


推荐阅读