search
HomeBackend DevelopmentPHP TutorialLinux--Terminal, job control, and daemons

1. The concepts of process group, job, and session
1. Process group: It is a collection of one or more processes. Typically, associated with the same job, various signals from the same terminal can be received. Each process has a unique process group ID. Each process group can have a leader process. The identity of the group leader process is that its process group ID is equal to its process ID. The group leader process can create a process group, create the processes in the group, and then terminate. As long as there is a process in a process group, the process group exists, regardless of whether the group leader process terminates.

2. Job: Shell is divided into front and backends to control not the process but the job (job) or process group. A foreground job can be composed of multiple processes, and a background job can also be composed of multiple processes. The shell can run a foreground job and any number of background jobs, which is called job control.

The difference between a job and a process group: If a process in the job creates a child process, the child process does not belong to the job.
Once the job ends, the Shell will bring itself to the foreground. If the original foreground process still exists (if the child process has not been terminated), it will automatically become a background process group.
3. Session: It is a collection of one or more process groups. A session can have one controlling terminal. The session first process that establishes a connection with the controlling terminal is called the controlling process. Several process groups in a session can be divided into a foreground process group and one or more background process groups. Therefore, a session should include the control process (the first process of the session), a foreground process group and any background process group.
**************** (The process group is equivalent to a class, and the group leader is equivalent to the squad leader. The conversation is equivalent to a grade. Each grade has an Academic Affairs Office .(control terminal)).
2. Terminal
1. The concept of terminal: After the user logs in to the system through the terminal, he gets a Shell process. This terminal is called the control terminal of the Shell process.
Each process can pass a special device file /dev/tty accesses its controlling terminal. In fact, each terminal device
corresponds to a different device file. /dev/tty provides a universal interface. A process can access its control terminal through /dev/tty or through the terminal device. Corresponding device file to access. The ttyname function can find out the corresponding file name from the file descriptor. The file descriptor must point to a terminal device and not any file.
******************Check the device file names corresponding to various terminals.

1 #include<stdio.h>  
  2 #include<unistd.h>  
  3 int main()  
  4 {  
  5     printf("fd: %d -> %s\n",0,ttyname(0));  
  6     printf("fd: %d -> %s\n",1,ttyname(1));  
  7     printf("fd: %d -> %s\n",2,ttyname(2));  
  8 }

2. Terminal login process:
A PC usually only has one set of keyboard and monitor, that is, only one set of terminal equipment, but it can be switched to 6 by Ctrl-Alt-F1~Ctrl-Alt-F6 Character terminals are equivalent to 6 sets of virtual terminal devices. They share the same set of physical terminal devices. The corresponding device files are /dev/tty1~/dev/tty6, so they are called virtual terminals. The device file /dev/tty0 represents the current virtual terminal. For example, when switching to the character terminal of Ctrl-Alt-F1, /dev/tty0 represents /dev/tty1. When switching to the character terminal of Ctrl-Alt-F2, /dev/tty0 represents Represents /dev/tty2, which is a universal interface just like /dev/tty, but it cannot represent the terminal corresponding to the graphical terminal window.
a. When the system starts, the init process determines which terminals need to be opened based on the configuration file /etc/inittab.
b. getty opens the terminal device as its control terminal according to the command line parameters, points the file descriptors 0, 1, and 2 to the control
terminal, and then prompts the user to enter an account. After the user enters the account, getty's task is completed, and it executes the login program:
execle("/bin/login", "login", "-p", username, NULL, envp);
c . The login program prompts the user to enter a password (turn off the terminal's echo during password input), and then verifies the correctness of the account password. If the password is incorrect, the login process is terminated, and init will re-fork/exec a getty process. If the password is correct, the login program sets some environment variables, sets the current working directory to the user's home directory, and then executes Shell:
execl("/bin/bash", "-bash", NULL);
三, Daemon process
1. The daemon process, also called the daemon process, is a special process running in the background. It is independent of the control terminal and periodically performs some task or waits for some event to occur.
2. Use ps axj | grep -E 'd$' to view the daemon process
Parameter a indicates that not only the processes of the current user are listed, but also the processes of all other users, and parameter x indicates that not only the processes of the control terminal are listed Process also lists all processes without control terminals. Parameter j indicates listing information related to job control.
3. Create a daemon process

Call the setsid function to create a new Session and become the Session Leader (session first process). The newly created Session id will be returned if the call is successful, and -1 will be returned on error;

a. Call umask to set the file mode creation mask to 0.
b. Call fork and the parent process exits (exit). Reasons:
1) If the daemon is started as a simple shell command, then the parent process termination causes the shell to think that the command has been executed.
2) Ensure that the child process is not the leader process of a process group.
c. Call setsid to create a new session. setsid will cause:
1) The calling process becomes the first process of the new session.
2) The calling process becomes the leader process of a process group.
3) The calling process does not have a controlling terminal. (Fork again to ensure that the daemon process will not open the tty device afterwards)
d. Change the current working directory to the root directory.
e. Close file descriptors that are no longer needed.
f, Others: Ignore the SIGCHLD signal.

#include<stdio.h>  
  2 #include<stdlib.h>  
  3 #include<unistd.h>  
  4 void mydeamon(void)  
  5 {  
  6     pid_t  id=fork();  
  7     umask(0);//将文件模式创建屏蔽字设置为0.  
  8     if(id>0)   
  9     {  
 10         exit(0);//调用fork,父进程退出(exit)  
 11     }  
 12     setsid();//调用setsid创建一个新会话  
 13     chdir("/");//将当前工作目录更改为根目录。  
 14     close(0);//关闭不在需要的文件描述符。  
 15     close(1);  
 16     close(2);  
 17 }  
 18 int main()  
 19 {  
 20     mydeamon();  
 21     while(1);  
 22     return 0;  
 23 }

Use ps axj |grep "file name" to view the daemon process just created

Linux--Terminal, job control, and daemons

The above is Linux--terminal, job control, and daemon process For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools