task_struct in the Linux Kernel: Every Field Explained

What is task_struct in the Linux kernel? A field by field guide to the process descriptor: pid, tgid, state, mm, files, cred, signals and scheduling.

task_struct in the Linux kernel, with pointers to mm_struct, files_struct and cred

task_struct is the C struct the Linux kernel uses to describe one task. A task is a process or a thread. Every running program on your Linux machine has at least one task_struct, and it holds or points to everything the kernel knows about that task: its state, its IDs, its parent, its memory, its open files, its signals and its scheduling data.

The struct is defined in include/linux/sched.h. It is also called the process descriptor.

This post is part of my series on C structs in the Linux kernel. In the first post I said the kernel is built out of structs. task_struct is the biggest example of that idea, so it gets a full post of its own.

Why is task_struct so big in the Linux kernel?

Because it has to answer every question the kernel may ask about a task. Is it running or sleeping? Who started it? Which memory does it use? Which files does it have open? Which signals is it waiting for? How much CPU time has it used?

In a modern kernel the struct has a few hundred fields. Many of them only exist when a certain config option is turned on, like lockdep, KASAN, NUMA balancing or perf. You do not need all of those to understand a process. So in this post I group the important fields into sections. For each section I show a short, simplified listing first. Then I explain each field: its type, what it means, and the older name if the field had a different name in 2.6 era kernels. Many tutorials and books still show the old names, so it helps to know both.

The field names here are checked against mainline include/linux/sched.h as of November 2026 (Linux 7.4-rc3). The listings below are trimmed. The real struct has more fields, and they are not in this exact order.

How does task_struct connect to other kernel structs?

Most of the heavy data is not stored inside task_struct itself. The struct holds pointers to other structs, and several tasks can share the same one. Threads of one program share one mm_struct, for example. Here is the picture:

   real_parent, parent
          ^
          |
  +-------+---------------+
  |      task_struct      |        +----------------+
  |                       |--mm--->| mm_struct      |  memory map
  |  __state, flags       |        +----------------+
  |  pid, tgid, comm      |        +----------------+
  |  prio, se, policy     |-files->| files_struct   |  open files
  |                       |        +----------------+
  |  children  (head) ----+--> list of child tasks
  |  sibling   (node) ----+--> link in parent's children list
  |  tasks     (node) ----+--> link in list of all processes
  |                       |        +----------------+
  |                       |--fs--->| fs_struct      |  root, cwd, umask
  |                       |        +----------------+
  |                       |        +----------------+
  |                       |-signal>| signal_struct  |  shared signal data, rlimits
  |                       |        +----------------+
  |                       |        +----------------+
  |                       |sighand>| sighand_struct |  signal handlers
  |                       |        +----------------+
  |                       |        +----------------+
  |                       |--cred->| cred           |  uid, gid, capabilities
  |                       |        +----------------+
  |                       |        +----------------+
  |                       |nsproxy>| nsproxy        |  namespaces
  +-----------------------+        +----------------+

The parent and child links are just pointers and list_head nodes inside task_struct. The arrows on the right are plain pointers. If two threads share memory, their mm pointers hold the same address.

Process state and flags in task_struct

struct task_struct {
    unsigned int   __state;      /* TASK_RUNNING, TASK_INTERRUPTIBLE, ... */
    unsigned int   saved_state;
    unsigned int   flags;        /* PF_* flags */
    unsigned int   ptrace;
    unsigned long  atomic_flags;
    unsigned long  jobctl;
    /* ... */
};
FieldTypeWhat it means
__stateunsigned intThe current state of the task. It holds values like TASK_RUNNING, TASK_INTERRUPTIBLE, TASK_UNINTERRUPTIBLE, __TASK_STOPPED or __TASK_TRACED. In 2.6 kernels this field was called state and was a long. It was renamed in Linux 5.14 so that code has to use helpers like READ_ONCE() and set_current_state() instead of touching it directly.
saved_stateunsigned intA place to keep the old state while a task sleeps on a lock in real time kernels. The kernel puts the old state back when the lock is taken.
flagsunsigned intPer task flags that start with PF_. For example PF_KTHREAD means this is a kernel thread, PF_EXITING means it is shutting down and PF_IDLE marks the idle task.
ptraceunsigned intNon zero when a debugger is tracing this task. It holds PT_* bits about how it is traced.
atomic_flagsunsigned longA second set of flags that must be changed atomically, like PFA_NO_NEW_PRIVS and some CPU security mitigation bits.
jobctlunsigned longJob control bits, used when a task is being stopped with SIGSTOP or traced.

What does a task state mean in plain words? TASK_RUNNING means the task is on a CPU or ready to run. TASK_INTERRUPTIBLE means it is sleeping and a signal can wake it up. TASK_UNINTERRUPTIBLE means it is sleeping and signals will not wake it. That is the D you see in ps. Newer kernels also combine bits, like TASK_KILLABLE, which is uninterruptible sleep that still wakes up for a fatal signal, and TASK_IDLE.

When you read State: in /proc/<pid>/status, the letter you see (R, S, D, T, Z and so on) comes from this field plus exit_state.

Identity: pid and tgid in the Linux kernel

struct task_struct {
    pid_t               pid;
    pid_t               tgid;
    struct pid         *thread_pid;
    struct hlist_node   pid_links[PIDTYPE_MAX];
    struct list_head    thread_node;
    char                comm[TASK_COMM_LEN];   /* TASK_COMM_LEN is 16 */
    /* ... */
};
FieldTypeWhat it means
pidpid_tThe ID of this one task. Every thread has its own pid. In user space this is what gettid() returns.
tgidpid_tThe thread group ID. It is the pid of the first thread in the group, the group leader. In user space this is what getpid() returns, so all threads of one program report the same number.
thread_pidstruct pid *A pointer to the kernel's struct pid object for this task. That object knows the task's number in each PID namespace.
pid_linksstruct hlist_node[]Links that hook this task onto the task lists of its struct pid objects, one per PID type (PID, TGID, PGID, SID). In 2.6 kernels this was the pids[] array, which was also used for the PID hash tables. The current layout came in around Linux 4.19.
thread_nodestruct list_headThis task's link in the list of all threads of its thread group. That list lives in signal_struct. Older kernels also had a thread_group list in the task itself.
commchar[16]The short name of the program, without the path. It is what ps and top show, and it is cut to 15 characters plus the ending zero. Kernel code should change it with set_task_comm().

So what is the difference between pid and tgid? For a single threaded program they are equal. When a program starts more threads, each new thread gets a new pid, but they all keep the leader's tgid. That is why the kernel calls a thread "a task" too. It is a full task_struct that shares some pointers with its siblings.

struct task_struct {
    struct task_struct __rcu  *real_parent;
    struct task_struct __rcu  *parent;
    struct list_head           children;
    struct list_head           sibling;
    struct task_struct        *group_leader;
    struct list_head           ptraced;
    struct list_head           ptrace_entry;
    struct list_head           tasks;
    /* ... */
};
FieldTypeWhat it means
real_parentstruct task_struct *The task that created this one with fork() or clone(). If that parent exits first, the child gets a new parent, usually init (PID 1) or a subreaper. This is what getppid() reports.
parentstruct task_struct *The task that gets notified with SIGCHLD and wait() results when this task changes state. It is normally the same as real_parent. It differs while a debugger is tracing the task with ptrace().
childrenstruct list_headThe head of the list of this task's children.
siblingstruct list_headThis task's node in its parent's children list. So the parent holds the list head and each child holds a node.
group_leaderstruct task_struct *Points to the leader of this thread group. For the leader it points to itself.
ptracedstruct list_headThe list of tasks this task is tracing as a debugger. In 2.6 kernels it was ptrace_children.
ptrace_entrystruct list_headThis task's node in its tracer's ptraced list. In 2.6 kernels it was ptrace_list.
tasksstruct list_headThis task's node in the big list of all processes. The list starts at init_task, the descriptor of process 0. The for_each_process() macro walks it.

The children, sibling and tasks fields are list_head nodes embedded in the struct. The kernel walks from a node back to its task_struct with container_of(). I will cover how that trick works in the linked list posts later, so I am keeping it short here.

Process group and session IDs used to be fields in the task too (pgrp and session in very old kernels, then signal->pgrp). Today the kernel gets them through signal_struct and struct pid.

Scheduling fields in the Linux kernel task_struct

struct task_struct {
    u8                           on_cpu;
    u8                           on_rq;
    int                          prio;
    int                          static_prio;
    int                          normal_prio;
    unsigned int                 rt_priority;
    struct sched_entity          se;
    struct sched_rt_entity       rt;
    struct sched_dl_entity       dl;
    const struct sched_class    *sched_class;
    unsigned int                 policy;
    int                          nr_cpus_allowed;
    const cpumask_t             *cpus_ptr;
    cpumask_t                    cpus_mask;
    int                          recent_used_cpu;
    int                          wake_cpu;
    struct sched_info            sched_info;
    unsigned long                nvcsw;
    unsigned long                nivcsw;
    /* ... */
};
FieldTypeWhat it means
on_cpuu8Set to 1 while the task is actually running on a CPU.
on_rqu8Says whether the task is on a run queue, meaning it is ready to run and waiting its turn.
priointThe priority the scheduler really uses right now. It can be raised for a short time, for example when this task holds a lock a higher priority task needs. Lower number means higher priority.
static_priointThe priority that comes from the nice value. Nice 0 maps to 120, nice -20 to 100 and nice 19 to 139.
normal_priointThe priority the task would have without any temporary boost. It is worked out from static_prio or rt_priority and the policy.
rt_priorityunsigned intThe real time priority, from 1 to 99, for tasks using SCHED_FIFO or SCHED_RR. It is 0 for normal tasks.
sestruct sched_entityThe data the fair scheduler (CFS, and EEVDF since 6.6) keeps for this task. It includes vruntime and sum_exec_runtime, the total CPU time used.
rtstruct sched_rt_entityData for the real time scheduler. Its run_list field links the task into a real time priority queue.
dlstruct sched_dl_entityData for the deadline scheduler (SCHED_DEADLINE), like runtime, deadline and period.
sched_classconst struct sched_class *A pointer to a table of functions for the scheduler class that owns this task: fair, real time, deadline, idle or stop. This is the kernel's "ops table" idea, which I will cover later in the series.
policyunsigned intThe scheduling policy: SCHED_NORMAL, SCHED_BATCH, SCHED_IDLE, SCHED_FIFO, SCHED_RR or SCHED_DEADLINE.
nr_cpus_allowedintHow many CPUs this task may run on.
cpus_maskcpumask_tThe set of CPUs this task may run on, the CPU affinity. taskset changes it. In 2.6 kernels it was called cpus_allowed. It was renamed in Linux 5.3.
cpus_ptrconst cpumask_t *A pointer the scheduler reads instead of cpus_mask directly. It normally points to cpus_mask, but it can point somewhere else for a short time, like when migration is disabled.
recent_used_cpuintA CPU this task ran on recently. The scheduler uses it to pick a warm CPU when the task wakes up.
wake_cpuintThe CPU picked to run the task when it is woken up.
sched_infostruct sched_infoScheduler statistics like how long the task waited on the run queue and how many times it ran.
nvcswunsigned longNumber of voluntary context switches. The task gave up the CPU on its own, for example to wait for I/O. Shown as voluntary_ctxt_switches in /proc/<pid>/status.
nivcswunsigned longNumber of involuntary context switches. The scheduler took the CPU away. Shown as nonvoluntary_ctxt_switches.

If you read older material you will see different scheduling fields. The 2.6 O(1) scheduler had run_list and array directly in the task, pointing into a prio_array_t with 140 priority lists. It also had sleep_avg, timestamp, last_ran, activated, time_slice and first_time_slice. All of those went away in Linux 2.6.23 when CFS arrived and the per task data moved into struct sched_entity se. The sched_class pointer came in at the same time.

Memory: mm and active_mm

struct task_struct {
    struct mm_struct  *mm;
    struct mm_struct  *active_mm;
    /* ... */
};
FieldTypeWhat it means
mmstruct mm_struct *The memory descriptor for this task's user address space. It holds the list of memory areas, the page tables and counters like resident memory. All threads of a process point to the same mm_struct. For kernel threads mm is NULL, because they have no user space.
active_mmstruct mm_struct *The address space that is actually loaded while this task runs. For normal tasks it equals mm. A kernel thread borrows the mm of the task that ran before it, so it does not have to switch page tables. This is called lazy TLB.

A simple test you will see in kernel code is if (!p->mm). It is one quick way to tell a kernel thread from a user task, though modern code prefers checking PF_KTHREAD in flags.

Credentials: cred and real_cred

struct task_struct {
    const struct cred __rcu  *ptracer_cred;
    const struct cred __rcu  *real_cred;
    const struct cred        *cred;
    /* ... */
};
FieldTypeWhat it means
real_credconst struct cred *The objective credentials. This is who the task really is when other tasks act on it, for example when someone sends it a signal.
credconst struct cred *The subjective credentials. This is who the task acts as when it opens a file or does other work. It is usually the same object as real_cred, but the kernel can override it for a short time.
ptracer_credconst struct cred *The credentials of the debugger at the moment it attached. Used for security checks while tracing.

Inside struct cred you find uid, gid, euid, egid, suid, sgid, fsuid, fsgid, the supplementary groups and the capability sets. In 2.6 kernels up to 2.6.28, those IDs were plain fields right inside task_struct, like current->uid and current->euid. Since 2.6.29 you read them through the cred, for example with current_uid() or task_euid(p). A cred is never changed in place. To change one the kernel makes a new copy and swaps the pointer.

Files and filesystem: files and fs

struct task_struct {
    struct fs_struct     *fs;
    struct files_struct  *files;
    struct nameidata     *nameidata;
    /* ... */
};
FieldTypeWhat it means
fsstruct fs_struct *Filesystem context: the root directory, the current working directory and the umask. chdir() and chroot() change what this points to.
filesstruct files_struct *The open file table. A file descriptor like 0, 1 or 3 is an index into the array of struct file pointers inside it. Threads usually share one files_struct.
nameidatastruct nameidata *Temporary state used while the kernel walks a path name like /home/me/a.txt.

Mainline also has a real_fs field next to fs. It is a very recent addition in the 7.x kernels and is not in 6.12, so you will not see it in most material yet.

When you run ls -l /proc/self/fd, the kernel is reading this task's files table. When you look at /proc/self/cwd, it reads fs.

Signals in the Linux kernel task_struct

struct task_struct {
    struct signal_struct         *signal;
    struct sighand_struct __rcu  *sighand;
    sigset_t                      blocked;
    sigset_t                      real_blocked;
    sigset_t                      saved_sigmask;
    struct sigpending             pending;
    unsigned long                 sas_ss_sp;
    size_t                        sas_ss_size;
    unsigned int                  sas_ss_flags;
    int                           pdeath_signal;
    /* ... */
};
FieldTypeWhat it means
signalstruct signal_struct *Signal and process wide data shared by all threads in the group. It has the shared pending signals, the thread list, resource limits in rlim[], process group and session info, and group wide CPU time totals.
sighandstruct sighand_struct *The table of signal handlers, what to do for each signal. Threads share it, which is why a handler set in one thread applies to all.
blockedsigset_tThe mask of signals this thread has blocked. sigprocmask() and pthread_sigmask() change it.
real_blockedsigset_tA saved copy of the mask, used by calls like rt_sigtimedwait() that change the mask for a while.
saved_sigmasksigset_tThe mask to restore after calls like sigsuspend() or ppoll() return.
pendingstruct sigpendingSignals sent to this one thread that are not handled yet. Signals sent to the whole process go into signal->shared_pending instead.
sas_ss_spunsigned longStart address of the alternate signal stack set with sigaltstack().
sas_ss_sizesize_tSize of that alternate stack.
sas_ss_flagsunsigned intFlags for the alternate stack.
pdeath_signalintThe signal this task gets when its parent dies. You set it with prctl(PR_SET_PDEATHSIG).

Resource limits like RLIMIT_NOFILE live in current->signal->rlim, not in the task. That has been the case since 2.6, and it is because limits are per process, not per thread.

Kernel stack and thread_info: where does the task live?

struct task_struct {
#ifdef CONFIG_THREAD_INFO_IN_TASK
    struct thread_info   thread_info;   /* must be first */
#endif
    void                *stack;
    refcount_t           stack_refcount;
    struct vm_struct    *stack_vm_area;
    /* ... */
    struct thread_struct thread;        /* must be last */
};
FieldTypeWhat it means
thread_infostruct thread_infoSmall, arch specific data that low level code needs fast, like the TIF_NEED_RESCHED and TIF_SIGPENDING flags. On x86 and arm64 it is the very first member of task_struct.
stackvoid *Points to the bottom of this task's kernel stack. Each task has its own kernel stack, used when it runs in kernel mode. On x86-64 it is 16 KB.
stack_vm_areastruct vm_struct *When the kernel stack is allocated with vmalloc (CONFIG_VMAP_STACK), this points to that area. A guard page there turns a stack overflow into a clean crash instead of silent memory damage.
stack_refcountrefcount_tA count of users of the stack, so it is not freed while someone still needs it.
threadstruct thread_structThe CPU specific saved state used during a context switch, like the saved stack pointer, segment and debug registers, and FPU state. It is kept as the last member because its size can change.

This is one of the areas that changed the most. In 2.6 kernels on x86, thread_info sat at the bottom of an 8 KB kernel stack area (a union thread_union). The task had a thread_info pointer to it and thread_info had a task pointer back. To find the current task, the kernel masked the low bits of the stack pointer to reach thread_info, then followed ->task. Today x86 sets CONFIG_THREAD_INFO_IN_TASK (since Linux 4.9), so thread_info moved inside task_struct and the stack area holds only the stack.

How does the Linux kernel find the current task_struct?

Kernel code writes current and gets a pointer to the running task. For example current->pid or current->comm.

On modern x86-64, current reads a per CPU variable called current_task. The scheduler writes the new task's address into it on every context switch, so reading it is a single instruction. Other architectures keep the pointer in a register, for example sp_el0 on arm64. On old 2.6 x86 kernels, current was found from the stack pointer as I described in the section above.

Time accounting fields in the Linux kernel task_struct

struct task_struct {
    u64            utime;
    u64            stime;
    u64            gtime;
    u64            start_time;
    u64            start_boottime;
    unsigned long  min_flt;
    unsigned long  maj_flt;
    struct task_io_accounting ioac;
    /* ... */
};
FieldTypeWhat it means
utimeu64CPU time this task spent in user mode, in nanoseconds.
stimeu64CPU time this task spent in kernel mode, in nanoseconds.
gtimeu64Time spent running a virtual machine guest, for KVM vCPU threads.
start_timeu64When the task started, in nanoseconds of monotonic time. Monotonic time does not count time while the machine was suspended.
start_boottimeu64When the task started, in nanoseconds since boot including suspend time. This is what feeds the start time column in /proc/<pid>/stat.
min_fltunsigned longMinor page faults: the page was already in memory and only needed mapping.
maj_fltunsigned longMajor page faults: the page had to be read from disk.
ioacstruct task_io_accountingBytes read and written, shown in /proc/<pid>/io.

In 2.6 kernels utime and stime were of type cputime_t, counted in ticks, and start_time was a struct timespec. Today they are plain u64 nanoseconds. Totals for the whole thread group, including dead threads, are kept in signal_struct.

Exit fields: exit_state, exit_code and exit_signal

struct task_struct {
    int  exit_state;
    int  exit_code;
    int  exit_signal;
    struct completion *vfork_done;
    int __user        *set_child_tid;
    int __user        *clear_child_tid;
    /* ... */
};
FieldTypeWhat it means
exit_stateintSet when the task has finished. EXIT_ZOMBIE means it is dead but the parent has not called wait() yet. EXIT_DEAD means it is being removed for good.
exit_codeintThe exit status and signal info that the parent reads with wait().
exit_signalintThe signal sent to the parent when this task exits, normally SIGCHLD. For threads it is -1, because a thread exiting does not notify the parent process.
vfork_donestruct completion *Used by vfork(). The parent sleeps on it until the child calls exec or exits.
set_child_tidint __user *A user space address where the kernel writes the new thread's ID at start. Thread libraries use it.
clear_child_tidint __user *A user space address that the kernel clears and wakes with a futex when the thread exits. This is how pthread_join() knows a thread is done.

A zombie is just a task_struct that stays around holding exit_code and the time totals until the parent collects them. Almost all its other resources are already freed.

Namespaces and cgroups: how containers use task_struct in the Linux kernel

struct task_struct {
    struct nsproxy        *nsproxy;
    struct css_set __rcu  *cgroups;
    struct list_head       cg_list;
    /* ... */
};
FieldTypeWhat it means
nsproxystruct nsproxy *Points to the set of namespaces the task lives in: UTS, IPC, mount, network, PID for children, time and cgroup. Containers are built on this. In early 2.6 kernels there was only a namespace field for mount namespaces. nsproxy came in 2.6.19.
cgroupsstruct css_set *The set of control groups this task belongs to. Limits like memory and CPU for containers and systemd services come from here.
cg_liststruct list_headThis task's node in the list of tasks that share the same css_set.

The user and PID namespaces are not stored directly in nsproxy for the task itself. The user namespace sits in cred, and the task's own PID namespace comes from its struct pid.

Reference counting and lifetime

struct task_struct {
    refcount_t       usage;
    refcount_t       rcu_users;
    struct rcu_head  rcu;
    spinlock_t       alloc_lock;
    raw_spinlock_t   pi_lock;
    /* ... */
};
FieldTypeWhat it means
usagerefcount_tHow many places hold a reference to this task_struct. get_task_struct() adds one and put_task_struct() drops one. The struct is freed when it reaches zero. In 2.6 kernels it was an atomic_t.
rcu_usersrefcount_tA second count for users that read the task under RCU. When it drops to zero, the kernel waits for an RCU grace period and then drops one usage reference.
rcustruct rcu_headUsed to free the task safely after all RCU readers are done.
alloc_lockspinlock_tProtects several pointers like mm, files, fs and comm while they are being changed. task_lock(p) takes it.
pi_lockraw_spinlock_tProtects the priority inheritance data and is also taken when waking the task up.

Why two counts? Many parts of the kernel only peek at a task under rcu_read_lock() and do not want to pay for a full reference. The two counters let both styles of access work.

Other fields worth knowing

These do not fit neatly in the groups above, but you will meet them when reading kernel code.

FieldTypeWhat it means
personalityunsigned intExecution domain flags, set with personality(). Used for things like disabling address space randomization for one program.
restart_blockstruct restart_blockInformation to restart a system call that was interrupted, like nanosleep().
stack_canaryunsigned longA random value used by the compiler's stack protector to catch stack smashing in kernel code.
seccompstruct seccompThe seccomp mode and filters for this task. Browsers and container runtimes use it to limit which system calls a process may make.
audit_contextstruct audit_context *Data for the audit subsystem while a system call is being audited.
loginuidkuid_tThe user ID that logged in, kept for auditing even after su or sudo.
sessionidunsigned intThe audit login session ID.
self_exec_idu64Goes up by one on every exec. The kernel uses it, for example, to decide if a child's exit signal should be reset because the parent ran a new program.
parent_exec_idu64The parent's self_exec_id at fork time.
journal_infovoid *Pointer used by journaling filesystems like ext4 to track the current transaction.
io_contextstruct io_context *Block I/O scheduler data for this task, like its I/O priority.
sysvsemstruct sysv_semSystem V semaphore undo info, so semaphore changes can be undone if the task dies.
mempolicystruct mempolicy *The NUMA memory policy set with set_mempolicy().
mems_allowednodemask_tThe NUMA nodes this task may take memory from, set by cpusets.
delaysstruct task_delay_info *Delay accounting: time spent waiting for CPU, I/O and memory.
task_worksstruct callback_head *A list of small jobs to run when the task next returns to user space.
io_uringstruct io_uring_task *Per task data for io_uring.
perf_event_ctxpstruct perf_event_context *Performance counter data used by perf.
securityvoid *Private data for security modules like SELinux or AppArmor.
timer_slack_nsu64How much the kernel may delay this task's timers to group wakeups and save power.
pagefault_disabledintCounter that is non zero while page faults are disabled for this task.

There are many more, mostly for debugging tools (lockdep, KASAN, KCSAN, KCOV, ftrace), NUMA balancing, real time locking and memory cgroups. They are each behind a config option, and most kernel developers never touch them.

How do you see task_struct fields from user space in Linux?

You cannot read task_struct directly from a normal program. It lives in kernel memory. But the kernel copies many of its fields out to you through system calls and through /proc.

Here is a small program that shows the difference between pid and tgid. It starts one extra thread and prints the IDs from both threads.

#define _GNU_SOURCE
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/syscall.h>

static void *worker(void *arg)
{
    (void)arg;
    /* getpid() returns tgid, gettid() returns this thread's own pid */
    printf("thread: getpid() = %d  gettid() = %ld\n",
           getpid(), (long)syscall(SYS_gettid));
    return NULL;
}

int main(void)
{
    pthread_t t;

    printf("main:   getpid() = %d  gettid() = %ld  getppid() = %d\n",
           getpid(), (long)syscall(SYS_gettid), getppid());

    pthread_create(&t, NULL, worker, NULL);
    pthread_join(t, NULL);
    return 0;
}

Build and run it:

gcc -Wall -o ids ids.c -pthread
./ids

Sample output (your numbers will differ):

main:   getpid() = 16724  gettid() = 16724  getppid() = 16707
thread: getpid() = 16724  gettid() = 16725

Both threads print the same getpid(). That is tgid. The thread has its own gettid(). That is its own pid field. The main thread is the group leader, so its pid and tgid match. getppid() comes from real_parent, which here is the shell.

The second program reads /proc/self/status. This file is built by the kernel from the current task_struct and the structs it points to. The program prints only the lines that map to the fields in this post.

#include <stdio.h>
#include <string.h>

/* Print the lines of /proc/self/status that come from task_struct */
int main(void)
{
    const char *keys[] = {
        "Name:", "State:", "Tgid:", "Pid:", "PPid:",
        "Uid:", "Gid:", "Threads:", "Cpus_allowed_list:",
        "voluntary_ctxt_switches:", "nonvoluntary_ctxt_switches:"
    };
    size_t nkeys = sizeof(keys) / sizeof(keys[0]);
    char line[256];
    FILE *f = fopen("/proc/self/status", "r");

    if (f == NULL) {
        perror("fopen");
        return 1;
    }

    while (fgets(line, sizeof(line), f) != NULL) {
        for (size_t i = 0; i < nkeys; i++) {
            if (strncmp(line, keys[i], strlen(keys[i])) == 0) {
                fputs(line, stdout);
                break;
            }
        }
    }

    fclose(f);
    return 0;
}
gcc -Wall -o status status.c
./status

Sample output:

Name:	status
State:	R (running)
Tgid:	16726
Pid:	16726
PPid:	16707
Uid:	1000	1000	1000	1000
Gid:	1000	1000	1000	1000
Threads:	1
Cpus_allowed_list:	0-7
voluntary_ctxt_switches:	0
nonvoluntary_ctxt_switches:	0

Here is where each line comes from:

/proc/self/status lineComes from
Namecomm
State__state and exit_state
Tgid, Pidtgid, pid (as seen in your PID namespace)
PPidreal_parent
Uid, Gidreal_cred (real, effective, saved and filesystem IDs)
Threadssignal->nr_threads
Cpus_allowed_listcpus_ptr
voluntary_ctxt_switchesnvcsw
nonvoluntary_ctxt_switchesnivcsw

The State is R because the program is running while it reads its own status. Try cat /proc/1/status or look at another process with ps and you will see S for sleeping.

A tiny Linux kernel module that reads task_struct

If you want to touch the real struct, a kernel module can. This one prints the task that loaded it, then walks the process list and prints the first ten tasks with their parent's PID.

// ts_demo.c: print the current task and the first few processes
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/sched/signal.h>   /* for_each_process() */
#include <linux/rcupdate.h>

static int __init ts_demo_init(void)
{
    struct task_struct *p;
    int n = 0;

    pr_info("ts_demo: loaded by %s, pid=%d tgid=%d\n",
            current->comm, current->pid, current->tgid);

    rcu_read_lock();
    for_each_process(p) {
        pr_info("ts_demo: %-16s pid=%d ppid=%d\n",
                p->comm, p->pid,
                rcu_dereference(p->real_parent)->tgid);
        if (++n >= 10)
            break;
    }
    rcu_read_unlock();
    return 0;
}

static void __exit ts_demo_exit(void)
{
    pr_info("ts_demo: unloaded\n");
}

module_init(ts_demo_init);
module_exit(ts_demo_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Walk task_struct fields from a module");

Note: I have not compiled or loaded this module. It is written against the mainline headers, but treat it as a sketch. To build it you need the headers for your running kernel and a two line Makefile with obj-m += ts_demo.o. After sudo insmod ts_demo.ko, read the output with sudo dmesg | tail, and remove it with sudo rmmod ts_demo.

A few things to notice. current is the task that ran insmod, so its comm is insmod. The walk is done inside rcu_read_lock(), because tasks can exit while we look at the list, and real_parent is an RCU protected pointer. Do not try this on a machine you care about. A bad pointer inside a module can crash the whole system.

That is the whole process descriptor, one group at a time. In the next posts of this C struct series we go back to smaller building blocks, and you will keep seeing pieces of task_struct as examples. If you want to get solid on C structs and pointers first, the Jupius C programming course covers them with live evaluation.

Frequently asked questions

What is task_struct in Linux?

task_struct is the C struct the Linux kernel uses to describe one process or thread. It holds the task's state, IDs, parent links, scheduling data and pointers to its memory, open files, credentials and signal handlers. It is also called the process descriptor.

Where is task_struct defined in the Linux kernel?

It is defined in include/linux/sched.h in the kernel source tree. Some parts it points to are defined elsewhere, like mm_struct in include/linux/mm_types.h and signal_struct in include/linux/sched/signal.h.

How big is task_struct?

It is several kilobytes on a typical modern 64-bit kernel, and the exact size varies with the kernel version, the CPU architecture and which config options are on. Distribution kernels with more debug and tracing options turned on are often bigger.

You can check the size on your own machine. One way is sudo grep task_struct /proc/slabinfo. The objsize column is the size of one task_struct in bytes. Another way, if you have the kernel debug info and the pahole tool, is to run pahole -C task_struct against the kernel's vmlinux.

What is the difference between pid and tgid in Linux?

pid is the ID of one task, and every thread has its own. tgid is the thread group ID, which is the pid of the first thread in the process. The getpid() call returns tgid, and gettid() returns pid.

How does the Linux kernel find the current task_struct?

Kernel code uses the current macro. On x86-64 it reads a per CPU variable that the scheduler updates on every context switch. Old 2.6 x86 kernels found it by masking the stack pointer to reach thread_info and then following its task pointer.

Is a thread a task_struct in Linux?

Yes. Every thread has its own task_struct with its own pid, state and kernel stack. Threads of the same process share the same tgid and point to the same mm_struct, files_struct, fs_struct, signal_struct and sighand_struct.

Continue with a course