LinuxFive States of a process
- Run
- Resumable
- Non-disruptive
- Botnets
- Stop
Traverse Parent and Child Processes
Note: The INIT process is statically allocated as init_struct.
Process Creation
In Linux, fork and exec are used to create processes. Fork creates a new process by copying the current process, and then loads the executable file and runs it through exec. Fork uses the write-time copy method to avoid unnecessary data copying, so that Linux can quickly create processes.
Fork
In Shell, when executing a command, ShellProgramThe Parent and Child processes are formed through "replication. After the child process is generated, execute the exec series functions, load new executable files, and start execution.
After the replication is complete, the child process is about to load a new program to run, and the memory space copied from the parent process is no longer needed. Therefore, in the "copy" process, copying memory space is a thankless task.
Therefore, fork has the "Copy at write time" technology. The memory is shared instead of being copied. It is not copied until one of the Parent and Child processes writes a block of memory. (The kernel first sets the memory to read-only. When they are written, the CPU encounters an access exception. The kernel captures an exception, copies the space, and changes the attribute to writable .)
Vfork
Vfork originated from 2.9bsd. The difference between vfork and fork is that it does not completely copy the address space of the parent process to the child process, because the child process will immediately call exec. The child process from vfork runs in the space of the parent process. It exists for exec calling, so it does not need to copy these things, because the replication is useless. If the sub-process modifies a variable, this will affect the parent process. Vfork ensures that the sub-process runs first. After it calls exec or exit, the parent process can be scheduled to run. Fork's Parent and Child processes run in an indefinite order, depending on the kernel scheduling.Algorithm.
LinuxThread implementation
Kernel thread
The kernel thread does not have an independent address space, and only runs and kernel space. The kernel thread is created through kernel_thread: