user1042891
user1042891

Reputation: 43

linux kernel/sched.c - find_process_by_pid - how to use it from a c application code

Linux-2.6.35.13 kernel/sched.c has a function find_process_by_pid(). I try with following code:

int main()
{
    struct task_struct *p;
    pid_t pid;
    pid=2130; 

    p = find_process_by_pid(pid);

    printf("task_struct.state: %s\n", p->state);
    return 0;
}

$ gcc getProcbyId.c -o getProcbyId

Get the following warning and error:

getProcbyId.c: In function 'main':
getProcbyId.c:19:4: warning: assignment makes pointer from integer without a cast
getProcbyId.c:21:37: error: dereferencing pointer to incomplete type

Please give advice how to solve this problem.

Upvotes: 1

Views: 1563

Answers (2)

Chris Stratton
Chris Stratton

Reputation: 40357

You cannot directly link user-mode application programs against internal kernel functionality. Instead, you are limited for reasons such as security and memory model differences (not to mention general design cleanliness) to interacting with exported functionality where the kernel applies appropriate checking and translations.

Syscalls are the tiny subset of kernel functions which are intended to be callable from userspace code, and this is not one of them.

The primary interface for finding out information about a foreign process is the PID entry under the /proc filesystem. Essentially this consist of a bunch of pseudo-files. Most of these are text files, and an attempt to read one will cause the kernel to collect and supply the appropriate information as if it were the contents of an actual file. You might be interested in the /proc/PID##/sched and possibly the similar files under the numbered thread subdirectories.

If you own a process you can ptrace() it and look around in that processes view of things, but that is more a case of proxying into the other process's userspace view than doing very much with the kernel's view of that process.

Upvotes: 7

sergico
sergico

Reputation: 2621

From a general point of view, the error seems caused by a missing header file in your code. The function returns a pointer to a struct: struct task_struct * but when you access a field of the struct the compiler need to know it's definition, hence the error

Anyway, are you sure you are allowed to call the above function from user space?

A document you might find useful on the topic (even though a bit old) is kernel - user space interfaces

Upvotes: 1

Related Questions