Home > System Tutorial > LINUX > body text

Learn more about processes: View child processes, thread information, and common statuses

PHPz
Release: 2024-07-25 08:00:14
Original
285 people have browsed it

Learn more about processes: View child processes, thread information, and common statuses

Q&A

ps View all child processes? pstree-ppid

ps-eLf What are the meanings of each array?

PID:process id 进程id
PPID: parent process id 父进程id
LWP:表示这是个线程;要么是主线程(进程),要么是线程
NLWP: num of light weight process 轻量级进程数量,即线程数量
TIME: 占用的CPU总时间
C CPU利用率,以整数表示。
Copy after login

View the cpu utilization rate/video memory/priority and other information of all threads under the process? top-H-p25120

See which CPU the thread is running on? ps-eoruser,pid,ppid,lwp,psr,args-L|grepl3-agent

Common process status?

-D:不可被唤醒的睡眠状态,通常用于 I/O 情况。
-R:该进程正在运行。
-S:该进程处于睡眠状态,可被唤醒。
-T:停止状态,可能是在后台暂停或进程处于除错状态。
-W:内存交互状态(从 2.6 内核开始无效)。
-X:死掉的进程(应该不会出现)。
-Z:僵尸进程。进程已经中止,但是部分程序还在内存当中。
-<:高优先级(以下状态在 BSD 格式中出现)。
-N:低优先级。
-L:被锁入内存。
-s:包含子进程。
-l:多线程(小写 L)。
-+:位于后台。
Copy after login

Six states of the process and its conversion process (life cycle) - ready state, running state, deep sleep state, light sleep state, stopped state, and zombie state.

What are the mother-child processes shared? the difference is? ——After fork, the mother and child processes share the file descriptor and the mapping area constructed by mmap. Others are copied, but the process space and even the process address of the process are completely the same as the parent process, and they are completely independent. space)

The difference between fork and vfork - vfork is used to create a new process, and the purpose of the new process is to exec a new program. Difference 1: The address space of the parent process is not copied to the child process. Difference 2: vfork ensures that the child process runs first. After it calls exec or (exit), the parent process can be scheduled to run.

**Is the address value of the shared video memory within the range of the user process space? **After fork, will the child process use the same address as the parent process? If they are different processes, are the addresses displayed in the process space of the shared video memory the same?

The life cycle of the process, ready state and running state are numerically equal and are defined by the macro TASK_RUNNING.

How is Task_struct managed in Linux?

Understand the zombie process - it gives up almost all the video memory space, has no executable code, and cannot be scheduled. It only retains a position in the process list (resources have long been released, and the Task_struct structure is still there). If its parent process does not install the SIGCHLD signal processing function and calls wait()/waitpid() to wait for the child process to end, and does not explicitly ignore the signal, then it will still remain in the zombie state. If the parent process ends, then the init process manually It will take over this child process and clean it up in the LINUX community. It can still be eliminated. If the parent process does not end, the child process will remain in the zombie state, which is why there are sometimes many zombie processes in the system. The process numbers that the system can use are limited (cat/proc/sys/kernel/pid_max). If a large number of zombie processes are formed, the system will not be able to form new processes because there are no available process numbers.

Subprocess recycling:

The parent process waits for the child process to end through wait/waitpid and other functions, which will cause the parent process to hang. If the parent process is very busy, you can use the signal function to install a handler for SIGCHLD. Because after the child process ends, the parent process will receive the signal and can call wait in the handler to recycle. If the parent process does not care when the child process ends, it can use signal (SIGCHLD, SIG_IGN) to notify the kernel that it is not interested in the end of the child process. After the child process ends, the kernel will recycle it and no longer send messages to the parent process. There are also some ways to signal, that is, fork twice. The parent process forks a child process and then continues to work. The child process forks a child process and then exits. In this way, the child process is taken over by init. After the child process ends, init will recycle it. However, you have to do the recycling of the child process yourself.

Why does the child process enter the zombie state after it ends? - Because the parent process may need to obtain the exit status and other information of the child process.

Is the zombie state a state that every child process must pass through? - Any child process (except init) does not disappear immediately after exit(), but leaves a data structure called a zombie process (Zombie) (It occupies some video memory resources, that is, there is still a record in the process table), waiting for the parent process to process. If the parent process does not have time to process the child process after exit(), then you can use the ps command to see that the status of the child process is "Z". If the parent process exits before the child process ends, the child process will be taken over by init. init will process the child process in zombie state as the parent process.

How to eliminate zombie processes:

Rewrite the parent process and collect the body of the child process after its death. The specific method is to accept the SIGCHLD signal. After the child process dies, the SIGCHLD signal is sent to the parent process. After the parent process receives this signal, it executes the waitpid() function to collect the corpse of the child process. This is based on the principle that even if the parent process does not call wait, the kernel will send it a SIGCHLD message. Although the default processing is to ignore it, if you want to respond to this message, you can set a processing function. SIGCHLD signal: When the child process ends, the parent process will receive this signal. If the parent process does not handle this signal and does not wait for the child process, the child process actually terminates and will occupy an entry in the kernel process table. At this time, the child process is called a zombie process. We should avoid this kind of situation (the parent process either ignores the SIGCHILD signal, or catches it, or waits for the child process it spawns, or the parent process terminates first, and then the termination of the child process is manually taken over by the init process) .

The exit() function when the process terminates, so what are the thread terminations? ——Three situations of thread abort:

The thread just returns from the startup function, and the return value is the exit code of the thread. Threads can be canceled by other threads in the same process. The thread calls pthread_exit.

If you are not waiting for a thread and are not interested in the return value of the thread, you can set the thread to the detached state and let the system manually reclaim the resources it occupies when the thread exits. A thread cannot call pthread_detach itself to change itself to the detached state. It can only call pthread_detach by other threads.

pthread_cancel() allows one thread to cancel another thread specified by th.

Process - the smallest unit of resource allocation, thread - the smallest unit of program execution. A process has an independent address space, and a thread does not have an independent address space (threads in the same process share the address space of the process). After a process crashes, it will not affect other processes in protected mode, and a thread is only a part of a process. Different execution paths. Threads have their own stacks and local variables, but threads do not have separate address spaces. If one thread hangs up, it means that the entire process has run away. Therefore, multi-process programs are stronger than multi-thread programs, but they consume more resources when switching processes. Larger, less efficient. However, for some concurrent operations that require simultaneous execution and sharing of individual variables, only threads, not processes, can be used.

Reason for using multi-threading?

Process

Process is the basic unit of resource allocation, and thread is the basic unit of scheduling

Process information

The Linux scheduler actually identifies task_struct for scheduling. Regardless of the process thread, the bottom layer corresponds to a task_struct. The difference between a process and a thread is the number of shared resources. There are no resources shared between the two processes, and all resources are shared between the two threads.

PCB(ProcessControlBlock) process control block

task_struct is the description of a process by the Linux kernel, which can also be called "process descriptor". A description of the structure that stores all the resources required by the process. /proc/${pid} process related information. To the operating system, a process is a data structure.

struct task_struct {
longstate; // 进程状态-1为不可运行, 0为可运行, >0为已中断

struct mm_struct*mm; // 指向的是进程的虚拟内存,也就是载入资源和可执行文件的地方
	pid_t pid; // 进程标识符,用来代表一个进程
 
struct task_struct __rcu*parent; // 指向父进程的指针
struct list_headchildren; // 子进程列表
 	struct list_head sibling; // 兄弟进程
struct fs_struct*fs;// 存放文件系统信息的指针
 
struct files_struct *files; // 一个数组,包含该进程打开的文件指针
unsigned int policy; // 调度策略:一般有FIFO,RR,CFS
...
};
Copy after login

从2.6版本之后,Linux改用了slab分配器动态生成task_struct,只须要在栈底(向上下降的栈)或栈顶(向下下降的栈)创建一个新的结构structthread_info(这儿是栈对象的尾端),你可以把slab分配器觉得是一种分配和释放数据结构的优化策略。通过预先分配和重复使用task_struct,可以防止动态分配和释放带来的资源消耗。

进程的地址空间ref

所谓进程地址空间(processaddressspace),就是从进程的视角听到的地址空间,是进程运行时所用到的虚拟地址的集合。

进程的显存

程序段(Text):程序代码在显存中的映射,储存函数体的二补码代码。

初始化过的数据(Data):在程序运行初早已对变量进行初始化的数据。

未初始化过的数据(BSS):在程序运行初未对变量进行初始化的数据。

栈(Stack):储存局部、临时变量,函数调用时,储存函数的返回表针,用于控制函数的调用和返回。在程序块开始时手动分配显存,结束时手动释放显存,其操作方法类似于数据结构中的栈。

堆(Heap):储存动态显存分配,须要程序员手工分配,手工释放.注意它与数据结构中的堆是两码事,分配方法类似于数组。

注:1.Text,BSS,Data段在编译时早已决定了进程将占用多少VM

可以通过size,晓得这种信息:

正常情况下,Linux进程不能对拿来储存程序代码的显存区域执行写操作,即程序代码是以只读的形式加载到显存中,但它可以被多个进程安全的共享。

创建进程后都创建了什么资源

进程创建

system()通过调用shell启动一个新进程

exec()以替换当前进程映像的方法启动一个新进程

fork()以复制当前进程映像的方法启动一个新进程

fork(2)

执行fork后,父进程的task_struck对拷给子进程,母子进程最初资源完全一样,而且是两份不同的拷贝,因而任何改动都导致两者的分裂。

兄妹进程对显存资源(mm)的管理使用了COW(Copy-On-Write,写时拷贝)技术:

在fork之前,一片显存区对应一份数学地址和一份虚拟地址,显存区的权限为RW;在fork以后,母子进程听到的显存区虚拟地址相同,化学地址也相同,母女进程使用的虽然是同一片化学显存,未发生显存拷贝,操作系统会将此显存区权限改为RO;父或子进程对显存区执行写操作将触发PageFault,操作系统此时会将显存区拷贝一份,母女进程见到的虚拟地址仍旧一样,而且化学地址早已不同。各进程虚拟地址到化学地址的映射由MMU(MemoryManagementUnit,显存管理单元)管理。fork运行在有MMU的CPU上。

Untuk CPU tanpa MMU, susah nak apply COW dan support fork. CPU tanpa MMU menggunakan vfork untuk mencipta proses, dan proses induk akan sentiasa menyekat sehingga proses anak keluar atau eksekutif. Perbezaan penting antara vfork dan fork ialah proses ibu dan anak dalam vfork berkongsi kawasan memori video yang sama.

Panggilan sistem

fork(2) digunakan untuk mencipta proses baharu, dipanggil proses anak, yang berjalan pada masa yang sama dengan proses induk (serentak), dan susunan berjalan tidak pasti (tak segerak). pid_t ialah takrifan makro, intipatinya ialah int Jika berjaya, ia mengembalikan dua nilai, proses anak mengembalikan 0, dan proses induk mengembalikan ID proses anak jika tidak, ralat mengembalikan -1

Seluruh ruang alamat maya ibu bapa disalin dalam proses anak, termasuk keadaan kunci mutex,

Proses anak adalah sama seperti proses ibu bapa, kecuali untuk perkara berikut:

Proses kitar semula wait() dan waitpid()

Kitar semula struktur tugas_struktur proses kanak-kanak melalui waitpid()/wait().

Perbezaan:

Proses Anak Yatim dan Proses Zombie Proses Zombie

Proses zombie: Proses menggunakan garpu untuk mencipta proses anak Jika proses anak keluar dan proses induk tidak memanggil tunggu atau tunggu untuk mendapatkan maklumat status proses anak, deskriptor proses proses anak sentiasa disimpan dalam. sistem. Proses ini dipanggil proses zombie. (Proses anak boleh dilihat melalui /proc/$pid, tetapi benangnya tidak)

Apabila proses memanggil arahan keluar untuk menamatkan hayatnya, walaupun ia tidak benar-benar musnah, ia meninggalkan struktur data yang dipanggil proses zombie (Zombie) (sistem memanggil keluar, fungsinya adalah untuk membuat proses Keluar, tetapi ia hanya terhad kepada menukar proses biasa kepada proses zombi, dan tidak boleh memusnahkannya sepenuhnya).

Dalam status proses Linux, proses zombi adalah jenis yang sangat istimewa Ia telah menyerahkan hampir semua ruang memori video, tidak mempunyai sebarang kod boleh laku, dan ia hanya mengekalkan kedudukan dalam senarai proses untuk merekodkan status proses. Status keluar dan maklumat lain boleh dikumpul oleh proses lain Selain itu, proses zombi tidak lagi menduduki mana-mana ruang memori video. Ia memerlukan proses induknya untuk mengumpul mayat untuknya.

Jika proses induknya tidak memasang fungsi pemprosesan isyarat SIGCHLD dan memanggil tunggu atau waitpid() untuk menunggu proses anak tamat, dan tidak mengabaikan isyarat secara jelas, maka ia masih akan kekal dalam keadaan zombi proses tamat pada masa ini, maka proses init Secara manual akan mengambil alih sub-proses ini dan mengumpul mayatnya, dan ia masih boleh dihapuskan.

Dan jika proses induk adalah gelung dan tidak akan berakhir, maka proses anak masih akan kekal dalam keadaan zombie Inilah sebabnya kadang-kadang terdapat banyak proses zombi dalam sistem. Nombor proses yang boleh digunakan oleh sistem adalah terhad Jika sejumlah besar proses zombie terbentuk, sistem tidak akan dapat membentuk proses baharu kerana tiada nombor proses yang tersedia.

Punca proses zombi: Selepas proses anak tamat, ia menghantar isyarat SIGCHLD kepada proses induk, dan proses induk mengabaikannya secara lalai; proses induk tidak memanggil fungsi wait() atau waitpid() untuk menunggu akhir proses kanak-kanak. Cara untuk menghalang proses zombi: Proses induk memanggil wait()/waitpid() untuk menunggu proses anak tamat Dengan cara ini, proses induk biasanya akan disekat dalam menunggu dan tidak dapat mengendalikan perkara lain. Tangkap isyarat SIGCHLD dan panggil fungsi tunggu pada fungsi pemprosesan isyarat Pemprosesan ini boleh menghalang masalah yang diterangkan dalam 1. Fork dua kali, proses ibu bapa mencipta proses bapa, dan proses bapa mencipta proses anak lelaki Selepas itu, proses ibu membunuh diri, dan proses anak menjadi anak yatim dan diambil oleh proses init. Proses anak yatim

Proses anak yatim: Proses induk keluar, tetapi satu atau lebih proses anak masih berjalan, jadi proses anak ini akan menjadi proses anak yatim. Proses anak yatim akan diambil oleh proses init (pid=1), dan proses init akan melengkapkan pengumpulan status untuk mereka. (Jika proses anak yatim muncul dalam sistem, ini bermakna proses utama tidak membersihkan proses kanak-kanak sebelum keluar)

Benang (LightweightProcess, LWP)

同一进程的多个线程获取进程ID时得到的是惟一ID值。Linux同一进程的多线程,在内核视角实际上每位线程都有一个PID,但在用户空间须要getpid()返回惟一值,Linux使用了一个小方法,引入了TGID的概念linux进程与线程 内核,getpid()返回的的TGID值。

pthread_create()

Linux线程本质上就是进程,只是与进程间资源共享方法不同,线程间共享所有资源。每位线程都有自己的task_struct,因而每位线程都可被CPU调度。多线程间又共享同一进程资源。

在一个线程中创建了另外一个线程,主线程要等到创建的线程返回了,获取该线程的返回值后主线程才退出。这个时侯就须要用到线程挂起。pthread_join函数用于挂起当前线程,直到指定的线程中止为止。

说线程的PID,是指用户空间的进程ID,值就是TGID(threadgroupIDforthethreadgroupleader);当非常强调,线程在内核空间的PID,则指线程在内核中task_struct里特有的PID。top–H命令从线程视角显示CPU占用率。不带参数的top命令,进程ID是主线程的PID(也就是TGID)。

Linux的进程和线程

进程是处于运行期的程序和相关资源的统称,具备一些要素:

拥有一段可执行程序代码。如同一场戏须要一个剧本。代码段可以多个进程共用,如同许多场表演都可以用一份剧本一样。拥有一段进程专用的系统堆栈空间。可以觉得是这个进程的“私有财产”,相应的,也肯定有系统空间堆栈在系统中有进程控制块(或称进程描述符,本文两种说法通用)描述这个进程的相关信息。可以觉得是进程的“户口”。系统通过这个控制块来控制进程的相关行为有独立的储存空间,也就是专有的用户空间,相应的又会有用户空间堆栈。理解各类ID

# ps -eo ppid,pid,tid,lwp,tgid,pgrp,sid,tpgid,args -L | awk &#039;{if(NR==1) print $0; if($9~/a.out/) print $0}&#039;
 PPID PID TID LWPTGIDPGRP SID TPGID COMMAND
 579046 2436128 2436128 2436128 2436128 2436128579046 2436128 ./a.out
 579046 2436128 2436129 2436129 2436128 2436128579046 2436128 ./a.out
 579046 2436128 2436130 2436130 2436128 2436128579046 2436128 ./a.out
Copy after login

pidstat-t[-ppid号]可以复印出线程之间的关系。

各类ID最后都归结到pid和lwp(tid)上。所以理解各类ID,最终归结为理解pid和lwp(tid)的联系和区别。

PID:进程ID。

LWP:线程ID。在用户态的命令(例如ps)中常用的显示方法。

TID:线程ID,等于LWP。TID在系统提供的插口函数中更常用,例如syscall(SYS_gettid)和syscall(__NR_gettid)。

TGID:线程组ID,也就是线程组leader的进程ID,等于PID。

pgid(processgroupID):进程组ID,也就是进程组leader的进程ID。

pthreadid:pthread库提供的ID,生效范围不在系统级别,可以忽视。

sid:sessionIDforthesessionleader。

TPGID:ttyprocessgroupIDfortheprocessgroupleader。

上图挺好地描述了用户视角(userview)和内核视角(kernelview)看见线程的差异:

轮询

Polling (benang peringkat pengguna), yang telus kepada kernel, iaitu, sistem tidak mengetahui kewujudan pengundian Ia sepenuhnya dijadualkan oleh program pengguna itu sendiri, kerana ia dikawal oleh program pengguna itu sendiri adalah sukar untuk Seperti menduduki penjadualan, yang memaksa kawalan CPU untuk beralih kepada proses/benang lain, secara amnya hanya penjadualan koperasi boleh dilakukan Selepas pengundian itu sendiri secara aktif menjual kawalan, pengundian lain boleh dilaksanakan.

Perbezaan antara goroutine dan interpreter

Pada asasnya, goroutine adalah pengundian. Perbezaannya ialah Golang merangkum dan memproses penjadualan goroutine dalam banyak aspek seperti masa jalan dan panggilan sistem Apabila ia menghadapi pelaksanaan jangka panjang atau panggilan sistem, ia akan secara aktif menjual CPU (P) goroutine semasa boleh operasi dan penyelenggaraan Linux yang dijadualkan dan dilaksanakan, iaitu, Golang menyokong penterjemah dari peringkat bahasa.

Penjadualan proses yang berbeza dalam aspek lain

Tiga strategi penjadualan utama kernel Linux:

1, SCHED_OTHER strategi penjadualan perkongsian masa,

2, strategi penjadualan masa nyata SCHED_FIFOproses linux dan inti utas, siapa cepat dia dapat

3, strategi penjadualan masa nyata SCHED_RR, putaran kepingan masa

Penjadualan proses masa nyata

SCHED_FIFO: Keutamaan yang berbeza dipindahkan ke tidur mengikut keutamaan yang lebih tinggi, dan kemudian dijalankan mengikut keutamaan yang lebih rendah, keutamaan yang sama ialah masuk dahulu, keluar dahulu.

SCHED_RR: Keutamaan yang berbeza akan dialihkan ke tidur mengikut keutamaan yang lebih tinggi, dan kemudian dijalankan mengikut keutamaan yang lebih rendah putaran keutamaan yang sama.

Tampalan RT kernel:

Dua parameter berikut

/proc/sys/kernel/sched_rt_period_us

/proc/sys/kernel/sched_rt_runtime_us

Menunjukkan bahawa RT hanya boleh berjalan sehingga masa runtime dalam tempoh tersebut

Penjadualan proses biasa

SCHED_OTHER:

CFS: Penjadualan Adil Sepenuhnya (irung baharu)

Paya bakau hitam, nilai nod kanan lebih besar daripada nilai nod kiri

Jalankan proses terkecil vruntime setakat ini

Memandangkan kedua-dua CPU/IO dan bagus

Sentiasa cari jadual urutan dengan vruntime terkecil.

vruntime=pruntime/weight×1024;

vruntime ialah masa larian maya, masa pruntime ialah masa larian kimia, dan berat ditentukan oleh nilai bagus (semakin rendah keanggunan, semakin tinggi berat Benang dengan masa larian yang kurang dan nilai bagus yang lebih rendah akan mempunyai lebih kecil). vruntime dan akan diutamakan untuk penjadualan. Ini adalah proses yang berubah secara dinamik dengan operasi.

Ruang kernel dan ruang pengguna Ruang kernel dan ruang pengguna

Ruang alamat maya Linux berjulat dari 0 hingga 4G Kernel Linux membahagikan ruang bait 4G ini kepada dua bahagian, dan bait 1G tertinggi (dari alamat maya 0xCxC0000000 hingga 0xFFFFFFFF) digunakan oleh kernel, yang dipanggil "ruang kernel. " ". Bait 3G yang lebih rendah (dari alamat maya 0x00000000 hingga 0xBFFFFFFF) digunakan oleh setiap proses, dipanggil "ruang pengguna. Oleh kerana setiap proses boleh melangkah ke dalam kernel melalui panggilan sistem, kernel Linux dikongsi oleh semua proses dalam sistem. . Jadi, dari perspektif proses tertentu, setiap proses boleh mempunyai 4G bait ruang maya

.

Linux menggunakan mekanisme perlindungan dua peringkat: Tahap 0 digunakan oleh kernel, dan Tahap 3 digunakan oleh program pengguna Setiap proses mempunyai ruang pengguna peribadinya sendiri (0~3G). Sistem tertinggi 1GB ruang kernel maya dikongsi oleh semua proses dan kernel.

Ruang kernel menyimpan kod dan data kernel, manakala ruang pengguna proses menyimpan kod dan data program pengguna. Sama ada ruang kernel atau ruang pengguna, semuanya berada dalam ruang maya. Sebenarnya, ruang kernel menduduki bait 1GB tertinggi bagi setiap ruang maya, tetapi ia sentiasa dipetakan ke memori kimia dari alamat terendah (0x00000000 Selain itu, penggunaan alamat maya dapat melindungi ruang kernel dengan berkesan daripada dimusnahkan). mengikut ruang pengguna. Alamat maya Proses penukaran alamat kimia diselesaikan oleh sistem pengendalian dan CPU bersama-sama (sistem pengendalian menetapkan jadual halaman untuk CPU, dan CPU melakukan penukaran alamat melalui unit MMU).

Nota: Setiap proses dalam sistem pengendalian berbilang tugas berjalan dalam kotak pasir memori videonya sendiri. Alamat maya ini dipetakan ke memori kimia melalui jadual halaman (pagetable), yang diselenggara oleh sistem pengendalian dan dirujuk oleh pemproses. Setiap proses mempunyai set jadual halaman sendiri.

Pengagihan ruang memori proses ditunjukkan di sebelah kanan:

Memori video

Timbunan turun dan timbunan naik (mengapa saya sebaliknya???)

Arah menurun dan endian besar dan kecil timbunan dan ingatan

Rendah->|----------------|

|Kuantiti global (semua kuantiti yang dimulakan.data, |

|Kuantiti yang tidak dimulakan.bss)|

Permulaan timbunan->|----------------|

|Timbunan jatuh ke arah alamat tinggi|

||

||

|Ruang kosong|

||

||

|Timbunan bergerak ke bawah ke alamat bawah|

Permulaan tindanan tinggi->|----------------|

The above is the detailed content of Learn more about processes: View child processes, thread information, and common statuses. For more information, please follow other related articles on the PHP Chinese website!

source:itcool.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!