Process Management (i)

Source: Internet
Author: User

(i): concept of the process

The thread is the object that is active in the process. Each thread has a separate program counter, a process stack, and a set of process registers. The kernel dispatches a thread rather than a process. In Linux, the differences between processes and threads are subtle, and we'll look at the two differences through the source code.

The process provides two virtual mechanisms, virtual processors, and virtual memory. Virtual memory can be shared between threads, but each thread has its own virtual processor.

In Linux, the function that creates a process is fork (), which is called to create a completely new process by copying an existing process. The process that calls fork () is called the parent process, and the process being created becomes a child process. The fork () system call returns two times from the kernel: once back to the parent process and back to the child process at once. Typically, a new process is created to execute a new, different program immediately, so after creating a new child process, the EXEC () function is called, which creates a new address space and loads the new program into the child process. Finally, the program exits execution through the exit () system call. This function will terminate the process and release the resources it occupies. The parent process can query whether the child process is terminated through the WAIT4 () system call, which in fact gives the process the ability to wait for a particular process to finish executing. After the process exits execution, it is set to a zombie state until its parent process calls wait () or waitpid ().

? exec function Family:
? defined in

intEXECL (Const Char*path,Const Char*arg, ...);intEXECLP (Const Char*file,Const Char*arg, ...);intExecle (Const Char*path,Const Char*arg, ...,Char*ConstEnvp[]);intExecvConst Char*path,Char*constargv[]);intEXECVP (Const Char*file,Char*constargv[]);intExecve (Const Char*path,Char*constargv[],Char*ConstEnvp[]);

? The parameter in the EXECV () function, the first parameter, const char *path, is the address of the program being run, and Char *constargv[] is the argument passed to the program being run.

Let's take a look at the creation of a process, executing the program and terminating it.

#include <unistd.h>#include <stdio.h>intMain () {intPid,status; PID =Fork();if(PID <0){printf("error!!"); }Else if(PID = =0){printf("I am the child forked!!, My pid is %d", Getpid ()); Execv"/bin/ls","-L"); }Else{printf("I am the parent!! My pid is %d", Getpid ());Waitpid(Pid,&status,0);printf("Child %d exit %d", pid,status); }return 0;}

This is just a simple example, through this example, you can expand more sub-processes, in fact, at the beginning of the kernel program, the program is created this way.
Here is the result of the program running:

(ii): Process descriptor and task structure

The kernel stores the list of processes in the task queue, which is a two-way circular chain. Each item in the list is a type task_struct struct, called a process descriptor. The structure is defined in the

structtask_struct {volatile LongState/*-1 unrunnable, 0 runnable, >0 stopped */    structThread_info *thread_info; atomic_t usage;unsigned LongFlags/ * per process flags, defined below * /    unsigned LongPtraceintlock_depth;/ * BKL Lock depth * /#ifdef CONFIG_SMP#ifdef __ARCH_WANT_UNLOCKED_CTXSW    intONCPU;#endif#endif    intLoad_weight;/ * For niceness load balancing purposes * /    intPrio, Static_prio, Normal_prio;structList_head run_list;structPrio_array *Array;unsigned  ShortIoprio;unsigned intBtrace_seq;unsigned LongSleep_avg;unsigned Long Longtimestamp, Last_ran;unsigned Long LongSched_time;/ * Sched_clock time spent running * /    enumSleep_type Sleep_type;unsigned LongPolicy cpumask_t cpus_allowed;unsigned intTime_slice, First_time_slice;#if defined (config_schedstats) | | defined (CONFIG_TASK_DELAY_ACCT)    structSched_info Sched_info;#endif    structList_head tasks;/ * * Ptrace_list/ptrace_children forms the list of my children * that were stolen by a ptracer. */    structList_head Ptrace_children;structList_head ptrace_list;structMm_struct *mm, *active_mm;/ * Task State * /    structLINUX_BINFMT *binfmt;LongExit_state;intExit_code, exit_signal;intpdeath_signal;/ * The signal sent when the parent dies * /    /* ??? */    unsigned LongPersonality;unsignedDid_exec:1;    pid_t pid; pid_t Tgid;/* * pointers to (original) The parent process, youngest child, younger sibling, * older sibling, respectively. (P->father can replaced with * p->parent->pid) */    structTask_struct *real_parent;/* Real parent process (when being debugged) */    structTask_struct *parent;/ * Parent Process * /    /* * children/sibling forms the list of my children plus the * tasks I ' m ptracing. */    structList_head children;/ * List of my children * /    structList_head sibling;/ * Linkage in my parent ' s children list * /    structTask_struct *group_leader;/ * Threadgroup leader * /    / * pid/pid Hash table linkage. * /    structPid_link Pids[pidtype_max];structList_head Thread_group;structCompletion *vfork_done;/* for vfork () */    int__user *set_child_tid;/ * Clone_child_settid * /    int__user *clear_child_tid;/ * Clone_child_cleartid * /    unsigned Longrt_priority; cputime_t Utime, stime;unsigned LongNVCSW, NIVCSW;/ * Context Switch counts * /    structTimespec start_time;/ * mm fault and swap info:this can arguably be seen as either mm-specific or thread-specific * /    unsigned LongMin_flt, Maj_flt; cputime_t It_prof_expires, It_virt_expires;unsigned Long LongIt_sched_expires;structList_head cpu_timers[3];/ * Process Credentials * /uid_t Uid,euid,suid,fsuid; gid_t Gid,egid,sgid,fsgid;structGroup_info *group_info; kernel_cap_t cap_effective, cap_inheritable, cap_permitted;unsignedKeep_capabilities:1;structUser_struct *user;#ifdef Config_keys    structKey *request_key_auth;/ * assumed request_key authority * /    structKey *thread_keyring;/ * Keyring Private to this thread * /    unsigned Charjit_keyring;/ * Default keyring to attach requested keys to * *#endif    intOomkilladj;/* OOM Kill score adjustment (bit shift). */    CharComm[task_comm_len];/* executable name excluding path-access with [Gs]et_task_comm (which lock It with Task_lock ())-initialized normally by flush_old_exec *// * File System info * /    intLink_count, Total_link_count;/ * IPC stuff * /    structSysv_sem Sysvsem;/* cpu-specific State of this task * /    structThread_struct thread;/ * FileSystem information * /    structFs_struct *fs;/ * Open File information * /    structFiles_struct *files;/ * namespace * /    struct namespace*namespace;/ * Signal handlers * /    structSignal_struct *signal;structSighand_struct *sighand;    sigset_t blocked, real_blocked; sigset_t Saved_sigmask;/* To is restored with tif_restore_sigmask * /    structSigpending pending;unsigned LongSAS_SS_SP; size_t Sas_ss_size;int(*notifier) (void*PRIV);void*notifier_data; sigset_t *notifier_mask;void*security;structAudit_context *audit_context; seccomp_t Seccomp;/ * THREAD Group Tracking * /U32 parent_exec_id; U32 self_exec_id;/* Protection of (de-) allocation:mm, files, FS, TTY, keyrings */spinlock_t Alloc_lock;/* Protection of the PI data structures: */spinlock_t Pi_lock;#ifdef config_rt_mutexes    / * PI Waiters blocked on a rt_mutex held by this task * /    structPlist_head pi_waiters;/ * Deadlock detection and priority inheritance handling * /    structRt_mutex_waiter *pi_blocked_on;#endif#ifdef config_debug_mutexes    / * Mutex deadlock detection * /    structMutex_waiter *blocked_on;#endif#ifdef config_trace_irqflags    unsigned intirq_events;inthardirqs_enabled;unsigned LongHARDIRQ_ENABLE_IP;unsigned intHardirq_enable_event;unsigned LongHARDIRQ_DISABLE_IP;unsigned intHardirq_disable_event;intsoftirqs_enabled;unsigned LongSOFTIRQ_DISABLE_IP;unsigned intSoftirq_disable_event;unsigned LongSOFTIRQ_ENABLE_IP;unsigned intSoftirq_enable_event;intHardirq_context;intSoftirq_context;#endif#ifdef CONFIG_LOCKDEP# define Max_lock_depth 30ULU64 Curr_chain_key;intlockdep_depth;structHeld_lock Held_locks[max_lock_depth];unsigned intLockdep_recursion;#endif/ * journalling FileSystem info * /    void*journal_info;/ * VM state * /    structReclaim_state *reclaim_state;structBacking_dev_info *backing_dev_info;structIo_context *io_context;unsigned LongPtrace_message; siginfo_t *last_siginfo;/ * for ptrace use. *// * * Current IO wait handle:wait queue entry to use for IO waits * If This thread is processing AIO, this points at t He waitqueue * Inside the currently handled KIOCB. The It May is NULL (i.e. default * to a stack based synchronous wait) if its doing sync IO. */wait_queue_t *io_wait;/* I/O counters (bytes read/written, #syscalls */U64 Rchar, WCHAR, SYSCR, SYSCW;#if defined (CONFIG_BSD_PROCESS_ACCT)U64 acct_rss_mem1;/ * Accumulated RSS usage * /U64 acct_vm_mem1;/ * Accumulated virtual memory usage * /clock_t ACCT_STIMEXPD;/ * clock_t-converted stime since last update * /#endif#ifdef Config_numa    structMempolicy *mempolicy; ShortIl_next;#endif#ifdef config_cpusets    structCpuset *cpuset; nodemask_t mems_allowed;intCpuset_mems_generation;intCpuset_mem_spread_rotor;#endif    structRobust_list_head __user *robust_list;#ifdef Config_compat    structCompat_robust_list_head __user *compat_robust_list;#endif    structList_head pi_state_list;structFutex_pi_state *pi_state_cache; atomic_t fs_excl;/ * Holding FS Exclusive resources * /    structRcu_head RCU;/ * * Cache last used pipe for splice */    structPipe_inode_info *splice_pipe;#ifdef CONFIG_TASK_DELAY_ACCT    structTask_delay_info *delays;#endif};

Process Management (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.