current->pid 如何为 linux 工作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10838342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 06:36:15  来源:igfitidea点击:

how does current->pid work for linux?

clinuxprocess

提问by randomizertech

Do I need to include a library? Can anyone please elaborate in it?

我需要包含一个库吗?任何人都可以请详细说明吗?

I know is used to get the process id of the current task where is being called from

我知道用于获取正在调用的当前任务的进程 ID

But I want to printk something with current->pid

但我想用 current->pid 打印一些东西

printk("My current process id/pid is %d\n", current->pid);

printk("My current process id/pid is %d\n", current->pid);

...and is giving me an error

...并给我一个错误

error: dereferencing pointer to incomplete type

error: dereferencing pointer to incomplete type

采纳答案by cnicutar

You're looking for #include <linux/sched.h>. That's where task_structis declared.

您正在寻找#include <linux/sched.h>. 这task_struct就是声明的地方。

回答by Rob I

I think you're looking for the getpid()system call. I don't know what currentis though.

我认为您正在寻找getpid()系统调用。我不知道是什么current

回答by betabandido

Your code should work. You are probably missing some header.

您的代码应该可以工作。您可能缺少一些标题。

currentis a per-cpu variable defined in linux/arch/x86/include/asm/current.h(all the code is for the case of x86):

current是一个 per-cpu 变量定义在linux/arch/x86/include/asm/current.h(所有代码都是针对 x86 的情况):

DECLARE_PER_CPU(struct task_struct *, current_task);
static __always_inline struct task_struct *get_current(void)
{
    return percpu_read_stable(current_task);
}
#define current get_current()

currentpoints to the task running on a CPU at a given moment. Its type is struct task_structand it is defined in linux/include/linux/sched.h:

current指向在给定时刻在 CPU 上运行的任务。它的类型是struct task_struct,定义在linux/include/linux/sched.h

struct task_struct {
    ...
    pid_t pid;   // process identifier
    pid_t tgid;  // process thread group id
    ...
};

You can browse the code for these files in the Linux Cross Reference:

您可以在Linux 交叉参考中浏览这些文件的代码: