• Definitions


Related Articles

Complete list of cybersecurity acronyms, human resources management system, how to defend yourself against identity theft, infographic, scalahosting, best managed service providers....


Dec 29, 2022

Linux Kernel — task_struct

As stated in my previous writeup about processes ( https://medium.com/@boutnaru/linux-processes-part-1-introduction-283f5b5b4197 ) every operating system has a data structure that represents a “process object” (generally called PCB — Process Control Block). By the way, “task_struct” is the PCB in Linux (it is also the TCB, meaning the Thread Control Block). As an example, a diagram that shows two processes opening the same file and the relationship between the two different “task_strcut” structures is shown below.

Overall, we can say that “task_struct” holds the data an operating system needs about a specific process. Among those data elements are: credentials ,priority, PID (process ID), PPID (parent process ID), list of open resources, memory space range information, namespace information ( https://medium.com/system-weakness/linux-namespaces-part-1-dcee9c40fb68 ), kprobes instances ( https://medium.com/@boutnaru/linux-instrumentation-part-2-kprobes-b089092c4cff ) and more.

Moreover, If you want to go over all of data elements I suggest going through the definition of “task_strcut” as part of the Linux source code — https://elixir.bootlin.com/linux/v6.2-rc1/source/include/linux/sched.h#L737 . Also, fun fact is that in kernel 6.2-rc1 “task_strcut” is referenced in 1398 files ( https://elixir.bootlin.com/linux/v6.2-rc1/A/ident/task_struct ).

Lastly, familiarity with “task_struct” can help a lot with tracing and debugging tasks as shown in the online book “Dynamic Tracing with DTrace & SystemTap” ( https://myaut.github.io/dtrace-stap-book/kernel/proc.html ). Also, it is very handy when working with bpftrace. For example sudo bpftrace -e ‘kfunc:hrtimer_wakeup { printf(“%s:%d\n”,curtask->comm,curtask->pid); }’, which prints the pid and the process name of all processes calling the kernel function hrtimer_wakeup ( https://medium.com/@boutnaru/the-linux-process-journey-pid-0-swapper-7868d1131316 ).

See you in my next writeup ;-)

You can follow me on twitter — @boutnaru ( https://twitter.com/boutnaru ).

More from Shlomi Boutnaru

About Help Terms Privacy

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store

Shlomi Boutnaru

Text to speech

Find start time of a process given PID

task_struct elixir

So I am stuck with this problem. I have to create a Loadable Kernel Module and implement a system call which returns the start time of a process given in PID. Please help me with this. Thanks

' src=

Ok, so first things first: you're in kernel land - you should basically never rely on usermode programs when you're in the kernel, and shouldn't rely on the VFS since you can directly interact with the underlying data instead of passing through the filesystem layer(s). In this case (as others have pointed out), this data is available in /proc/<pid>/stat and others, so let's see how those sources get the data:

In the source for the procfs subsystem ( https://elixir.bootlin.com/linux/v5.0.9/source/fs/proc ), we find the do_task_stat function ( https://elixir.bootlin.com/linux/v5.0.9/source/fs/proc/array.c#L430 ) which handles the VFS read to /proc/<pid>/stat . Inside of this, there's a line with convenient variable names ( https://elixir.bootlin.com/linux/v5.0.9/source/fs/proc/array.c#L536 ):

As you can see, the real_start_time is a field in the task struct. A bit of background since it sounds like you're just getting started: the task_struct structure ( https://elixir.bootlin.com/linux/v5.0.9/source/include/linux/sched.h#L592 ) is the core kernel structure that represents a single "task" the kernel should schedule (normally thought of as a "thread" in userland). This holds basically all of the data the kernel has about a task (or at least has pointers to just about everything associated with the task), so it makes sense that the field would be in there.

Now, the next question is: how can we get a task_struct* from an int pid . Looking through the source for the PID-related functions ( https://elixir.bootlin.com/linux/v5.0.9/source/kernel/pid.c ), there's a number of methods that would be useful depending on the namespace you want to get the PID from. Another quick aside: Linux has the idea of different namespaces for a few types of things the kernel handles (PIDs, network, IPC, etc.). In certain situations (e.g. containers) new namespaces are created, and processes are created within that namespace context. These namespaces are completely independent of other namespaces, so PID 1 in a container (i.e. in a non-init PID namespace) may not be PID 1 on the host (i.e. in the init PID namespace). PIDs within a namespace are referred to as VPIDs (Virtual Process IDs).

Hope that gives you some insight.

Thank you so much 👍🏻

I'm not a programmer, so i'm not sure the exact calls needed for your purposes, but the information you're looking for is available in /proc, specifically /proc/[PID]/stat and /proc/uptime

/proc/[pid]/stat Status information about the process. This is used by ps(1). It is defined in /usr/src/linux/fs/proc/array.c. ... ... starttime %llu (was %lu before Linux 2.6) The time in jiffies the process started after system boot.

starttime is field 22 in /proc/[pid]/stat

$ awk '{print $22}' /proc/[pid]/stat

Jiffies is probably 100 ($ getconf CLK_TCK / sysconf(_SC_CLK_TCK); ) so divide the starttime by that for the total seconds that the process was started after boot, which can be found in /proc/uptime

/proc/uptime This file contains two numbers: the uptime of the system (seconds), and the amount of time spent in idle process (seconds).

then uptime - pid_starttime is time pid has been running in seconds.



There is probably a cleaner way of doing this, but you could use the stat function. The returned stat struct should have what you need if you point it at /proc/<PID>.


Thank you. But I am a beginner. Is there any example code which can show me exactly how to get the start time from proc/pid using the stat.

About Community

Subreddit Icon

Ranked by Size

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Where is task_struct stored?

Task_struct is used for keeping necessary information about a process by kernel. Thanks to that structure kernel can suspend a process and after a while proceed with its implementation. But my question is: where is this task_struct stored in memory (I've read about kernel stack, is that one which is in kernel space of virtual address space?)? where does kernel keep a pointer to that structure and that structure after suspending process?

I would appreciate if you give some references to resources where it's described.

PS. I forgot to say the question is about Linux kernel.

Allok's user avatar

4 Answers 4

The Linux kernel allocates a task_struct via the kmem_cache facility. For instance in fork.c there is a piece of code responsible for allocating a task struct:

The place where the pointer to the current thread is stored is architecture-dependent. For instance, this is how it works for x86 (arch/x86/include/asm/current.h):

and in PowerPC (arch/powerpc/include/asm/current.h):

You can use the Elixir Cross Reference in order to easily explore the kernel source.

betabandido's user avatar

task_struct is allocated with the help of slab allocator. Each task in kernel has kernel stack of either 8kb or 4kb which can never increase or decrease.

If we talk specific to 0x86 architecture, then at the end of task kernel stack, we have thread_info struct which essentially stores/points the task_struct pointer. And task_struct has the kernel stack pointer which can be decreased by 8kb to get thread info struct.

Ritesh's user avatar

From the perspective of Virtual memory system, task_struct is allocated by the Slab allocator, so that it's located in the kernel space . More specifically, slab memory can be directly mapped into cache.

asap diablo's user avatar

The kernel structures that handle thread and process context are OS-dependent. Typically, they would be allocated from a non-paged pool, as will be the collection/s of pointers to them that are used to manage them.

Martin James's user avatar

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged linux process kernel task or ask your own question .

Hot Network Questions

task_struct elixir

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

VIDEOS 》 Linux Operating System - User-space Processes

Refer: Linux Kernel Source: struct task_struct data-structure - http://elixir.free-electrons.com/linux/latest/ ... Task state bitmask flags - tsk->state - http://elixir.free-electrons.com/linux/latest/ ... struct task_struct instance example1: TASK_RUNNING, TASK_INTERRUPTIBLE, TASK_UNINTERRUPTIBLE, TASK_STOPPED - http://elixir.free-electrons.com/linux/latest/ ... struct task_struct instance example2: struct task_struct *p - p->state == TASK_RUNNING - http://elixir.free-electrons.com/linux/latest/ ... ----- Images: Linux Process task state - http://www.macdesign.net/capella/it4813/images ... Linux Kernel sub-systems - https://i.pinimg.com/originals/a4/76/e5/a476e5 ... Linux system architecture - http://technozed.com/wp-content/uploads/2016/0 ... Linux system architecture Image2 - https://image.slidesharecdn.com/linuxkernelarc ... Java JVM architecture - http://2.bp.blogspot.com/-4g8GW68TQy4/T0J4DOqk ... Kernel type: Monolithic-Kernel, Micro-Kernel and Hybrid-Kernel examples - https://upload.wikimedia.org/wikipedia/commons ... Android OS on top of Linux Kernel (OS): Andrid architecture - https://www.androidauthority.com/wp-content/up ...

Here is the struct task_struct data-structure data-structure ( /include/linux/sched.h ) from the Kernel-source version 4.14 for quick reference: struct task_struct { #ifdef CONFIG_THREAD_INFO_IN_TASK /* * For reasons of header soup (see current_thread_info()), this * must be the first element of task_struct. */ struct thread_info thread_info; #endif /* -1 unrunnable, 0 runnable, >0 stopped: */ volatile long state; /* * This begins the randomizable portion of task_struct. Only * scheduling-critical items should be added above here. */ randomized_struct_fields_start void *stack; atomic_t usage; /* Per task flags (PF_*), defined further below: */ unsigned int flags; unsigned int ptrace; #ifdef CONFIG_SMP struct llist_node wake_entry; int on_cpu; #ifdef CONFIG_THREAD_INFO_IN_TASK /* Current CPU: */ unsigned int cpu; #endif unsigned int wakee_flips; unsigned long wakee_flip_decay_ts; struct task_struct *last_wakee; int wake_cpu; #endif int on_rq; int prio; int static_prio; int normal_prio; unsigned int rt_priority; const struct sched_class *sched_class; struct sched_entity se; struct sched_rt_entity rt; #ifdef CONFIG_CGROUP_SCHED struct task_group *sched_task_group; #endif struct sched_dl_entity dl; #ifdef CONFIG_PREEMPT_NOTIFIERS /* List of struct preempt_notifier: */ struct hlist_head preempt_notifiers; #endif #ifdef CONFIG_BLK_DEV_IO_TRACE unsigned int btrace_seq; #endif unsigned int policy; int nr_cpus_allowed; cpumask_t cpus_allowed; #ifdef CONFIG_PREEMPT_RCU int rcu_read_lock_nesting; union rcu_special rcu_read_unlock_special; struct list_head rcu_node_entry; struct rcu_node *rcu_blocked_node; #endif /* #ifdef CONFIG_PREEMPT_RCU */ #ifdef CONFIG_TASKS_RCU unsigned long rcu_tasks_nvcsw; u8 rcu_tasks_holdout; u8 rcu_tasks_idx; int rcu_tasks_idle_cpu; struct list_head rcu_tasks_holdout_list; #endif /* #ifdef CONFIG_TASKS_RCU */ struct sched_info sched_info; struct list_head tasks; #ifdef CONFIG_SMP struct plist_node pushable_tasks; struct rb_node pushable_dl_tasks; #endif struct mm_struct *mm; struct mm_struct *active_mm; /* Per-thread vma caching: */ struct vmacache vmacache; #ifdef SPLIT_RSS_COUNTING struct task_rss_stat rss_stat; #endif int exit_state; int exit_code; int exit_signal; /* The signal sent when the parent dies: */ int pdeath_signal; /* JOBCTL_*, siglock protected: */ unsigned long jobctl; /* Used for emulating ABI behavior of previous Linux versions: */ unsigned int personality; /* Scheduler bits, serialized by scheduler locks: */ unsigned sched_reset_on_fork:1; unsigned sched_contributes_to_load:1; unsigned sched_migrated:1; unsigned sched_remote_wakeup:1; /* Force alignment to the next boundary: */ unsigned :0; /* Unserialized, strictly 'current' */ /* Bit to tell LSMs we're in execve(): */ unsigned in_execve:1; unsigned in_iowait:1; #ifndef TIF_RESTORE_SIGMASK unsigned restore_sigmask:1; #endif #ifdef CONFIG_MEMCG unsigned memcg_may_oom:1; #ifndef CONFIG_SLOB unsigned memcg_kmem_skip_account:1; #endif #endif #ifdef CONFIG_COMPAT_BRK unsigned brk_randomized:1; #endif #ifdef CONFIG_CGROUPS /* disallow userland-initiated cgroup migration */ unsigned no_cgroup_migration:1; #endif unsigned long atomic_flags; /* Flags requiring atomic access. */ struct restart_block restart_block; pid_t pid; pid_t tgid; #ifdef CONFIG_CC_STACKPROTECTOR /* Canary value for the -fstack-protector GCC feature: */ unsigned long stack_canary; #endif /* * Pointers to the (original) parent process, youngest child, younger sibling, * older sibling, respectively. (p->father can be replaced with * p->real_parent->pid) */ /* Real parent process: */ struct task_struct __rcu *real_parent; /* Recipient of SIGCHLD, wait4() reports: */ struct task_struct __rcu *parent; /* * Children/sibling form the list of natural children: */ struct list_head children; struct list_head sibling; struct task_struct *group_leader; /* * 'ptraced' is the list of tasks this task is using ptrace() on. * * This includes both natural children and PTRACE_ATTACH targets. * 'ptrace_entry' is this task's link on the p->parent->ptraced list. */ struct list_head ptraced; struct list_head ptrace_entry; /* PID/PID hash table linkage. */ struct pid_link pids[PIDTYPE_MAX]; struct list_head thread_group; struct list_head thread_node; struct completion *vfork_done; /* CLONE_CHILD_SETTID: */ int __user *set_child_tid; /* CLONE_CHILD_CLEARTID: */ int __user *clear_child_tid; u64 utime; u64 stime; #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME u64 utimescaled; u64 stimescaled; #endif u64 gtime; struct prev_cputime prev_cputime; #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN struct vtime vtime; #endif #ifdef CONFIG_NO_HZ_FULL atomic_t tick_dep_mask; #endif /* Context switch counts: */ unsigned long nvcsw; unsigned long nivcsw; /* Monotonic time in nsecs: */ u64 start_time; /* Boot based time in nsecs: */ u64 real_start_time; /* MM fault and swap info: this can arguably be seen as either mm-specific or thread-specific: */ unsigned long min_flt; unsigned long maj_flt; #ifdef CONFIG_POSIX_TIMERS struct task_cputime cputime_expires; struct list_head cpu_timers[3]; #endif /* Process credentials: */ /* Tracer's credentials at attach: */ const struct cred __rcu *ptracer_cred; /* Objective and real subjective task credentials (COW): */ const struct cred __rcu *real_cred; /* Effective (overridable) subjective task credentials (COW): */ const struct cred __rcu *cred; /* * executable name, excluding path. * * - normally initialized setup_new_exec() * - access it with [gs]et_task_comm() * - lock it with task_lock() */ char comm[TASK_COMM_LEN]; struct nameidata *nameidata; #ifdef CONFIG_SYSVIPC struct sysv_sem sysvsem; struct sysv_shm sysvshm; #endif #ifdef CONFIG_DETECT_HUNG_TASK unsigned long last_switch_count; #endif /* Filesystem information: */ struct fs_struct *fs; /* Open file information: */ struct files_struct *files; /* Namespaces: */ struct nsproxy *nsproxy; /* Signal handlers: */ struct signal_struct *signal; struct sighand_struct *sighand; sigset_t blocked; sigset_t real_blocked; /* Restored if set_restore_sigmask() was used: */ sigset_t saved_sigmask; struct sigpending pending; unsigned long sas_ss_sp; size_t sas_ss_size; unsigned int sas_ss_flags; struct callback_head *task_works; struct audit_context *audit_context; #ifdef CONFIG_AUDITSYSCALL kuid_t loginuid; unsigned int sessionid; #endif struct seccomp seccomp; /* Thread group tracking: */ u32 parent_exec_id; u32 self_exec_id; /* Protection against (de-)allocation: mm, files, fs, tty, keyrings, mems_allowed, mempolicy: */ spinlock_t alloc_lock; /* Protection of the PI data structures: */ raw_spinlock_t pi_lock; struct wake_q_node wake_q; #ifdef CONFIG_RT_MUTEXES /* PI waiters blocked on a rt_mutex held by this task: */ struct rb_root_cached pi_waiters; /* Updated under owner's pi_lock and rq lock */ struct task_struct *pi_top_task; /* Deadlock detection and priority inheritance handling: */ struct rt_mutex_waiter *pi_blocked_on; #endif #ifdef CONFIG_DEBUG_MUTEXES /* Mutex deadlock detection: */ struct mutex_waiter *blocked_on; #endif #ifdef CONFIG_TRACE_IRQFLAGS unsigned int irq_events; unsigned long hardirq_enable_ip; unsigned long hardirq_disable_ip; unsigned int hardirq_enable_event; unsigned int hardirq_disable_event; int hardirqs_enabled; int hardirq_context; unsigned long softirq_disable_ip; unsigned long softirq_enable_ip; unsigned int softirq_disable_event; unsigned int softirq_enable_event; int softirqs_enabled; int softirq_context; #endif #ifdef CONFIG_LOCKDEP # define MAX_LOCK_DEPTH 48UL u64 curr_chain_key; int lockdep_depth; unsigned int lockdep_recursion; struct held_lock held_locks[MAX_LOCK_DEPTH]; #endif #ifdef CONFIG_LOCKDEP_CROSSRELEASE #define MAX_XHLOCKS_NR 64UL struct hist_lock *xhlocks; /* Crossrelease history locks */ unsigned int xhlock_idx; /* For restoring at history boundaries */ unsigned int xhlock_idx_hist[XHLOCK_CTX_NR]; unsigned int hist_id; /* For overwrite check at each context exit */ unsigned int hist_id_save[XHLOCK_CTX_NR]; #endif #ifdef CONFIG_UBSAN unsigned int in_ubsan; #endif /* Journalling filesystem info: */ void *journal_info; /* Stacked block device info: */ struct bio_list *bio_list; #ifdef CONFIG_BLOCK /* Stack plugging: */ struct blk_plug *plug; #endif /* VM state: */ struct reclaim_state *reclaim_state; struct backing_dev_info *backing_dev_info; struct io_context *io_context; /* Ptrace state: */ unsigned long ptrace_message; siginfo_t *last_siginfo; struct task_io_accounting ioac; #ifdef CONFIG_TASK_XACCT /* Accumulated RSS usage: */ u64 acct_rss_mem1; /* Accumulated virtual memory usage: */ u64 acct_vm_mem1; /* stime + utime since last update: */ u64 acct_timexpd; #endif #ifdef CONFIG_CPUSETS /* Protected by ->alloc_lock: */ nodemask_t mems_allowed; /* Seqence number to catch updates: */ seqcount_t mems_allowed_seq; int cpuset_mem_spread_rotor; int cpuset_slab_spread_rotor; #endif #ifdef CONFIG_CGROUPS /* Control Group info protected by css_set_lock: */ struct css_set __rcu *cgroups; /* cg_list protected by css_set_lock and tsk->alloc_lock: */ struct list_head cg_list; #endif #ifdef CONFIG_INTEL_RDT u32 closid; u32 rmid; #endif #ifdef CONFIG_FUTEX struct robust_list_head __user *robust_list; #ifdef CONFIG_COMPAT struct compat_robust_list_head __user *compat_robust_list; #endif struct list_head pi_state_list; struct futex_pi_state *pi_state_cache; #endif #ifdef CONFIG_PERF_EVENTS struct perf_event_context *perf_event_ctxp[perf_nr_task_contexts]; struct mutex perf_event_mutex; struct list_head perf_event_list; #endif #ifdef CONFIG_DEBUG_PREEMPT unsigned long preempt_disable_ip; #endif #ifdef CONFIG_NUMA /* Protected by alloc_lock: */ struct mempolicy *mempolicy; short il_prev; short pref_node_fork; #endif #ifdef CONFIG_NUMA_BALANCING int numa_scan_seq; unsigned int numa_scan_period; unsigned int numa_scan_period_max; int numa_preferred_nid; unsigned long numa_migrate_retry; /* Migration stamp: */ u64 node_stamp; u64 last_task_numa_placement; u64 last_sum_exec_runtime; struct callback_head numa_work; struct list_head numa_entry; struct numa_group *numa_group; /* * numa_faults is an array split into four regions: * faults_memory, faults_cpu, faults_memory_buffer, faults_cpu_buffer * in this precise order. * * faults_memory: Exponential decaying average of faults on a per-node * basis. Scheduling placement decisions are made based on these * counts. The values remain static for the duration of a PTE scan. * faults_cpu: Track the nodes the process was running on when a NUMA * hinting fault was incurred. * faults_memory_buffer and faults_cpu_buffer: Record faults per node * during the current scan window. When the scan completes, the counts * in faults_memory and faults_cpu decay and these values are copied. */ unsigned long *numa_faults; unsigned long total_numa_faults; /* * numa_faults_locality tracks if faults recorded during the last * scan window were remote/local or failed to migrate. The task scan * period is adapted based on the locality of the faults with different * weights depending on whether they were shared or private faults */ unsigned long numa_faults_locality[3]; unsigned long numa_pages_migrated; #endif /* CONFIG_NUMA_BALANCING */ struct tlbflush_unmap_batch tlb_ubc; struct rcu_head rcu; /* Cache last used pipe for splice(): */ struct pipe_inode_info *splice_pipe; struct page_frag task_frag; #ifdef CONFIG_TASK_DELAY_ACCT struct task_delay_info *delays; #endif #ifdef CONFIG_FAULT_INJECTION int make_it_fail; unsigned int fail_nth; #endif /* * When (nr_dirtied >= nr_dirtied_pause), it's time to call * balance_dirty_pages() for a dirty throttling pause: */ int nr_dirtied; int nr_dirtied_pause; /* Start of a write-and-pause period: */ unsigned long dirty_paused_when; #ifdef CONFIG_LATENCYTOP int latency_record_count; struct latency_record latency_record[LT_SAVECOUNT]; #endif /* * Time slack values; these are used to round up poll() and * select() etc timeout values. These are in nanoseconds. */ u64 timer_slack_ns; u64 default_timer_slack_ns; #ifdef CONFIG_KASAN unsigned int kasan_depth; #endif #ifdef CONFIG_FUNCTION_GRAPH_TRACER /* Index of current stored address in ret_stack: */ int curr_ret_stack; /* Stack of return addresses for return function tracing: */ struct ftrace_ret_stack *ret_stack; /* Timestamp for last schedule: */ unsigned long long ftrace_timestamp; /* * Number of functions that haven't been traced * because of depth overrun: */ atomic_t trace_overrun; /* Pause tracing: */ atomic_t tracing_graph_pause; #endif #ifdef CONFIG_TRACING /* State flags for use by tracers: */ unsigned long trace; /* Bitmask and counter of trace recursion: */ unsigned long trace_recursion; #endif /* CONFIG_TRACING */ #ifdef CONFIG_KCOV /* Coverage collection mode enabled for this task (0 if disabled): */ enum kcov_mode kcov_mode; /* Size of the kcov_area: */ unsigned int kcov_size; /* Buffer for coverage collection: */ void *kcov_area; /* KCOV descriptor wired with this task or NULL: */ struct kcov *kcov; #endif #ifdef CONFIG_MEMCG struct mem_cgroup *memcg_in_oom; gfp_t memcg_oom_gfp_mask; int memcg_oom_order; /* Number of pages to reclaim on returning to userland: */ unsigned int memcg_nr_pages_over_high; #endif #ifdef CONFIG_UPROBES struct uprobe_task *utask; #endif #if defined(CONFIG_BCACHE) || defined(CONFIG_BCACHE_MODULE) unsigned int sequential_io; unsigned int sequential_io_avg; #endif #ifdef CONFIG_DEBUG_ATOMIC_SLEEP unsigned long task_state_change; #endif int pagefault_disabled; #ifdef CONFIG_MMU struct task_struct *oom_reaper_list; #endif #ifdef CONFIG_VMAP_STACK struct vm_struct *stack_vm_area; #endif #ifdef CONFIG_THREAD_INFO_IN_TASK /* A live task holds one reference: */ atomic_t stack_refcount; #endif #ifdef CONFIG_LIVEPATCH int patch_state; #endif #ifdef CONFIG_SECURITY /* Used by LSM modules for access restriction: */ void *security; #endif /* * New fields for task_struct should be added above here, so that * they are included in the randomized portion of task_struct. */ randomized_struct_fields_end /* CPU-specific state of this task: */ struct thread_struct thread; /* * WARNING: on x86, 'thread_struct' contains a variable-sized * structure. It *MUST* be at the end of 'task_struct'. * * Do not put anything below here! */ };

Here is the task state bitmask representing process states ( /include/linux/sched.h ) from the Kernel-source version 4.14 for quick reference: /* * Task state bitmask. NOTE! These bits are also * encoded in fs/proc/array.c: get_task_state(). * * We have two separate sets of flags: task->state * is about runnability, while task->exit_state are * about the task exiting. Confusing, but this way * modifying one set can't modify the other one by * mistake. */ /* Used in tsk->state: */ #define TASK_RUNNING 0x0000 #define TASK_INTERRUPTIBLE 0x0001 #define TASK_UNINTERRUPTIBLE 0x0002 #define __TASK_STOPPED 0x0004 #define __TASK_TRACED 0x0008 /* Used in tsk->exit_state: */ #define EXIT_DEAD 0x0010 #define EXIT_ZOMBIE 0x0020 #define EXIT_TRACE (EXIT_ZOMBIE | EXIT_DEAD) /* Used in tsk->state again: */ #define TASK_PARKED 0x0040 #define TASK_DEAD 0x0080 #define TASK_WAKEKILL 0x0100 #define TASK_WAKING 0x0200 #define TASK_NOLOAD 0x0400 #define TASK_NEW 0x0800 #define TASK_STATE_MAX 0x1000 /* Convenience macros for the sake of set_current_state: */ #define TASK_KILLABLE (TASK_WAKEKILL | TASK_UNINTERRUPTIBLE) #define TASK_STOPPED (TASK_WAKEKILL | __TASK_STOPPED) #define TASK_TRACED (TASK_WAKEKILL | __TASK_TRACED) #define TASK_IDLE (TASK_UNINTERRUPTIBLE | TASK_NOLOAD) /* Convenience macros for the sake of wake_up(): */ #define TASK_NORMAL (TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE) #define TASK_ALL (TASK_NORMAL | __TASK_STOPPED | __TASK_TRACED) /* get_task_state(): */ #define TASK_REPORT (TASK_RUNNING | TASK_INTERRUPTIBLE | \ TASK_UNINTERRUPTIBLE | __TASK_STOPPED | \ __TASK_TRACED | EXIT_DEAD | EXIT_ZOMBIE | \ TASK_PARKED)

Refer: Linux Kernel Source: struct task_struct data-structure - http://elixir.free-electrons.com/linux/latest/ ... struct mm_struct data-structure - http://elixir.free-electrons.com/linux/latest/ ... Task state bitmask flags - tsk->state - http://elixir.free-electrons.com/linux/latest/ ...

/exe symlink points to */ struct file __rcu *exe_file; #ifdef CONFIG_MMU_NOTIFIER struct mmu_notifier_mm *mmu_notifier_mm; #endif #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !USE_SPLIT_PMD_PTLOCKS pgtable_t pmd_huge_pte; /* protected by page_table_lock */ #endif #ifdef CONFIG_CPUMASK_OFFSTACK struct cpumask cpumask_allocation; #endif #ifdef CONFIG_NUMA_BALANCING /* * numa_next_scan is the next time that the PTEs will be marked * pte_numa. NUMA hinting faults will gather statistics and migrate * pages to new nodes if necessary. */ unsigned long numa_next_scan; /* Restart point for scanning and setting pte_numa */ unsigned long numa_scan_offset; /* numa_scan_seq prevents two threads setting pte_numa */ int numa_scan_seq; #endif /* * An operation with batched TLB flushing is going on. Anything that * can move process memory needs to flush the TLB when moving a * PROT_NONE or PROT_NUMA mapped page. */ atomic_t tlb_flush_pending; #ifdef CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH /* See flush_tlb_batched_pending() */ bool tlb_flush_batched; #endif struct uprobes_state uprobes_state; #ifdef CONFIG_HUGETLB_PAGE atomic_long_t hugetlb_usage; #endif struct work_struct async_put_work; #if IS_ENABLED(CONFIG_HMM) /* HMM needs to track a few things per mm */ struct hmm *hmm; #endif } __randomize_layout;

Suggested Topics:

task_struct elixir

Join The Linux Channel :: Facebook Group ↗

Visit The Linux Channel :: on Youtube ↗

💗 Help shape the future: Sponsor/Donate

task_struct elixir

Support, Donate and Contribute - The Linux Channel ↗ Saturday' 13-Mar-2021 Help shape the future and make an impact by donating/sponsor The Linux Channel. Your donation will transform lives !

Research Socket overhead in Linux vs Message Queues and benchmarking ↗ Saturday' 13-Mar-2021

task_struct elixir

KERNEL - The Linux Channel - a High Performance Linux Kernel ↗ Saturday' 13-Mar-2021

Stack Exchange Network

Stack Exchange network consists of 181 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

When we create a new a process, where in the linux kernel is its priority assigned?

I am using Linux 4.19.2 https://elixir.bootlin.com/linux/v4.19.2/ident/

I figured out the structure called task_struct which contains all the information in the Process Control Block. When we create a new process, the fork() function is called, which in turn, calls functions like _do_fork() and copy_process() to provide values for the fields in task_struct .

However, I couldn't find out where is the priority of a new process. The field name used for priority in the task_struct structure is prio . Where does it get its value from, when a process is started?

Rui F Ribeiro's user avatar

I tried figuring it out from this link https://elixir.bootlin.com/linux/v4.19.2/ident/

This provides a Linux kernels cross-referenced, that I can read. I figured out that to fork a new process, the function _do_fork() calls copy_process() which in turn calls a function called sched_fork() .

This is where the priority of the process is initialised using the function normal_prio() .

ctrl-alt-delor's user avatar

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged linux-kernel or ask your own question .

Hot Network Questions

task_struct elixir

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

Arm Linux Kernel Hacks


포토로그 Kernel Crash

통계 위젯 (화이트)

[Linux Kernel] Armv8: where is cpu_context_save? 4. 프로세스(Process) 관리

task_struct elixir


  1. Linux kernel study notes (four) process management

    task_struct elixir

  2. Linux进程管理(一)

    task_struct elixir

  3. Linux 進程源碼分析 task_struct_禅与计算机程序设计艺术的博客-CSDN博客

    task_struct elixir

  4. Linux Kernel: What is the relationship between kthread and task_struct structure?

    task_struct elixir

  5. 搜集的一些task_struct结构示意图_yiyeguzhou100的专栏-CSDN博客

    task_struct elixir

  6. linux-进程-01-进程和fork

    task_struct elixir


  1. [Master Elixir] 10

  2. Struct Task 2

  3. Struct Task 1

  4. Neelu aur Neelima ki kahani part 40/the task barbie/doll gude gudiaa cartoon barbie




  1. What Is a Task Environment?

    An organization’s task environment is the collection of factors that affects its ability to achieve goals. Common factors in the task environment include competitors, customers, suppliers and distributors.

  2. What Is Task Interdependence?

    Task interdependence sets rules and guidelines for the sharing of expertise, materials and information between members of an organization working on interdependent tasks.

  3. What is Struct?

    A struct, or structure, in C programming languages is a container that holds variables of different data types that can be accessed together. Structs are A struct, or structure, in C programming languages is a container that holds variables...

  4. task_struct identifier

    Elixir Cross Referencer - Explore source code in your browser - Particularly useful for the Linux kernel and other low-level projects in C/C++ (bootloaders

  5. task_struct identifier

    Elixir Cross Referencer - Explore source code in your browser - Particularly useful for the Linux kernel and other low-level projects in C/C++ (bootloaders

  6. Linux Kernel

    ... is that in kernel 6.2-rc1 “task_strcut” is referenced in 1398 files (https://elixir.bootlin.com/linux/v6.2-rc1/A/ident/task_struct).

  7. Find start time of a process given PID : r/kernel

    Now, the next question is: how can we get a task_struct* from an int pid .

  8. task_struct

    struct task_struct { /* * offsets of these are hardcoded elsewhere - touch with care */ volatile long state; /* -1 unrunnable, 0 runnable, >

  9. How 'task_struct' is accessed via 'thread_info' in linux latest kernel?

    But when I checked the same structure in the latest linux code, I see a very different thread_info structure as below. (https://elixir.bootlin.

  10. Where is task_struct stored?

    The Linux kernel allocates a task_struct via the kmem_cache facility. ... You can use the Elixir Cross Reference in order to easily explore

  11. Linux Operating System

    Task state bitmask flags - tsk->state

  12. When we create a new a process, where in the linux kernel is its

    I tried figuring it out from this link https://elixir.bootlin.com/linux/v4.19.2/ident/. This provides a Linux kernels cross-referenced

  13. where is cpu_context_save?

    In case of ARM64 Linux kernel, struct task_struct.thread.cpu_context saves context information of process when preemption occurs. https://elixir

  14. When I see Kernel thread task_struct, its mm_struct filed is ...

    linux/kernel - Elixir - Free Electrons.