11.1. The 5 states of the process state and system function and process relationship
(1) process; Ready state-The process is currently all running conditions ready, as long as the CPU time to be able to run directly, run state-ready state when the CPU running time to enter the running state began to run Zombie state-The child process has ended but the parent process has not yet been able to reclaim the body of the subprocess; wait state (shallow sleep & deep sleep)-the process waits for some condition, the condition is ripe to enter the ready state, in the waiting state even to the CPU running time scheduling the process can not be executed, The process can be awakened (signal/resource in place) while the shallow sleep is waiting the process cannot be awakened while the deep sleep is waiting for the condition to end the sleep state; Pause state-Pause is not the end of the process, the process is paused (signal), and can be restored (signal) (see Figure 1).
(2) the system function; the effect is equivalent to Fork+exec, which is atomic operation, that is, once the entire operation is not interrupted after the execution, the benefits of atomic operations will not be interrupted (will not attract competition), the disadvantage is that their own continuous CPU time to take up too long to affect the overall system real-time, You should try to avoid unnecessary atomic operations, even if you have to do atomic operations as much as possible to shorten the atomic operation time.
(3) process relationship; no relationship-two processes are completely independent, most processes in the operating system are not related to each other, the code inside the process is not accessible to other processes, the parent-child process relationship-two processes have parent-child relationships, and two processes are tightly connected, The child process inherits all operations before the parent process fork; Process groups-a group of 1 processes consisting of several processes that make up a tightly connected process of 1 process groups in order to facilitate the management process; session-a session is a group of process groups, consisting of groups of multiple process groups, The same is to facilitate the management process.
11.2. Introduction of Daemon
(1) Process view command PS;PS-AJX (displays the various relevant ID numbers for all processes of the operating system); Ps-aux (shows the various resources occupied by all processes of the operating system); Send signal to process kill;kill-signal number _ Process ID (sending a signal to a process); Kill-9_xxx (sending the 9th signal to the XXX process, ending the process). The
(2) daemon is daemon, for the short term d, the process name followed by D is basically the daemon process; The daemon is long-running and normally runs until the shutdown is over, the daemon is detached from the console, and the normal process is bound to the console that runs the process. When the where terminal is forced to close, all processes running in the terminal are closed because all processes under that terminal are subordinate to the same console session. The
(3) server program, which is a program that is always running, can provide us with some kind of service (for example, NFS server provides us with NFS communication), When our program needs some kind of service, we can call the server program (through and server communication to get the server program Help) to do service operation, server programs are generally implemented as daemons.
(4) Common daemon processes, syslogd-system log daemons, providing syslog functionality (ps-aux|grep "SYSLOGD"), and cron-implementing the time management of the operating system, the function of implementing timer programs in Linux is to use cron.
(5) Any process can implement itself as a daemon; Createdaemon function element-subprocess waits for the parent process to exit + subprocess uses SETSID to create a new session to detach from console + Invoke ChDir set the current working directory to/root directory + Umask is set to 0 to remove any file permission masks + to close all file descriptors + 0, 1, 2 to locate the/dev/null Recycle Bin.
11.3. Logging debug information using Syslog
(1) We can use the Syslog log to record the debugging information generated by the process during the operation by openlog/syslog/closelog these 3 functions, log information is commonly stored in the operating system's/var/log/messages file, But Ubuntu is stored in the/var/log/syslog file.
(2) There is a daemon in the operating system syslogd (power on, shutdown when the end), the daemon syslogd responsible for log file writing and maintenance; syslogd is independent of any process, our current process and the SYSLOGD process have no relationship, However, our current process can open and syslogd connected channels by calling Openlog, and then send messages via syslog to SYSLOGD, which are then written to the log file system by SYSLOGD.
(3) syslogd is actually 1 log file system server process, providing logging service, any process that needs to write logs can use the openlog/syslog/closelog of these 3 functions to take advantage of the SYSLOGD provided by the log service, the second is the operating system's service-style design.
11.4. Let the program not be run multiple times
(1) Because the daemon is running for a long time without exiting, so./ The a.out executes 1 times and has 1 processes, there are multiple processes to execute; Our daemons are typically servers, and server programs run 1 of them, and it doesn't make sense or even cause errors to run multiple times, so we want the program to have a single running function, which is when we./ A.out to run the program, if the program is not currently running the process is run, if the process has previously been running the program is run, this run directly exit (the prompt program is already running).
(2) The most common method is to use the existence of a file or not to do the logo, the program at the beginning of the execution to determine whether a particular file exists, if the existence of the process is already running, if it does not exist to indicate that the process is not running, and then run the program to create the file, when the program is finished to delete the file, This particular file should be a bit odd to make sure it doesn't happen to be in the computer.
11.5.linux interprocess Communication Overview
(1) interprocess communication IPC refers to communication between 2 arbitrary processes; When a process is in the same address space, communication between different modules within the process (different functions/files) is simple and can be achieved through global variables/ function parameter arguments, but 2 different processes are in different address spaces, so it is difficult to communicate with each other. The program for
(2) 99% does not need to consider interprocess communication, because most programs are now single process, they commonly use multithreading to solve concurrency problems; complex/large programs are designed to be programmed into multiple processes, that is, the entire program is designed to work at the same time to complete the pattern, Common such as GUI system/server, so the IPC technology in the general small and medium programs are not used, in large programs will only use. The
(3) Linux kernel provides a variety of interprocess communication mechanisms, nameless pipes and well-known pipelines (the earliest available communication between parent-child processes), semaphores + Message Queuing + Shared memory (developed by Systemv_ipc_unix); Socket domain sockets (network traffic, The communication between different processes on two different computers on the network is developed by Bsd_unix.
(4) Why we do not study IPC in detail; less daily use, only large programs can be used (such as Aliyun server program at the bottom of the development), learning more complex, belongs to the most difficult part of Linux application programming, more details, involved in the function and parameters of the details are very much less involved in the interview, It is not helpful to find a job. It is suggested that the following in-depth study to write the actual code detailed discussion.
11.6. Famous Pipes and nameless pipes
(1) pipe (default nameless pipe)-two processes communicate through a block of memory maintained in the kernel; the pipe has read and write ends and must be set to simplex communication to prevent read-write conflicts; Two single pipe can be established to achieve duplex communication.
(2) method of pipeline communication-the parent process first creates a pipe and then fork the child process, inherits the pipeline FD of the parent process, and then turns off the read/write end in the parent process, and then turns off the write/read end in the subprocess.
(3) Pipe communication restrictions-only communication between parent-child processes + a single pipe can only be realized in one-line communication; function of pipe communication-pipe (Create pipe)/write (write pipe)/read (read pipe)/close (Close pipe).
(4) A well-known pipeline (FIFO)-two processes communicate through a block of memory maintained in the kernel, the representation is 1 named files; How to use a well-known pipe-fixed 1 file names first, 2 processes use Mkfifo to create FIFO files, and then open access to FD separately. Then 1 read 1 write.
(5) A well-known pipeline communication restrictions-single pipe can only achieve the one-worker communication (note that the parent-child process, any 2 processes can); a function-mkfifo (creating a FIFO file) for a pipe communication is/open/write/read/close.
11.7.SystemV IPC Introduction
(1) The basic characteristics of SYSTEMV_IPC-the system through a number of proprietary APIs to provide SYSTEMV_IPC functions, a total of signal volume + Message Queuing + shared memory, its essence is through the core provided by the public memory to communicate.
(2) Message Queuing-essentially 1 queues, which can be understood as FIFO, which is maintained by the kernel, where a and B2 processes communicate, a messages are placed in the queue, B reads messages from the queue (for broadcast/unicast).
(3) Semaphore-the essence is a counter, essentially 1 variables that can be counted, can be interpreted as a variable of 1 int types, and the values are used to provide mutual exclusion and synchronization (for mutual exclusion and synchronization).
(4) Shared memory-large chunks of memory in the kernel are mapped directly to two different processes to solve large capacity/fast information exchange; a process for camera capture, b process for video encoding, c process to send encoded data to the network, The a process and the B process are mapped to the same memory in the kernel for data collection and coding, similar to the memory usage for LCD display (for a large amount of data exchange between the two processes).
11.system * * Company: XXXX * Author: Rston * Blog: Http://blog.csdn.net/rston * github:https://github.com
/rston * Project: Process relationship and interprocess communication * Function: Demonstrates the simple use of the system function.
* * #include <stdio.h> #include <stdlib.h> int main (int argc, char **argv) {int ret =-1;
RET = System ("Ls-la");
if (Ret < 0) {perror ("system error");
Exit (-1);
return 0; }
11.daemon/* Company: XXXX * Author: Rston * Blog: Http://blog.csdn.net/rston * Github:https://github.com/rston * Project: Process relationship and interprocess communication
* Function: Create daemon. * #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include &l
t;sys/stat.h> #include <fcntl.h>//function declares void Creatdaemon (void);
int main (int argc, char **argv) {Creatdaemon ();
while (1) {printf ("I am running.\n");
Sleep (1);
return 0;
///Turn the process calling the function into 1 daemons void Creatdaemon (void) {pid_t pid =-1;
PID = fork (); if (PID > 0) {exit (0);
The parent process exits directly} else if (0 = = pid) {//Setsid sets the current process to 1 new session sessions, leaving the current process out of the console PID = Setsid ();
if (PID < 0) {perror ("Setsid error");
Exit (-1);
///Set the current process working directory to the root directory chdir ("/");
Umask is set to 0 to ensure that future processes have the maximum file operation rights umask (0); Closes all file descriptors//Gets the maximum text allowed on the current systemNumber of pieces of descriptor int cnt = sysconf (_sc_open_max);
int i = 0;
For (i=0. i<cnt; i++) {close (i);
///0, 1, 2 positioning to the/dev/null Recycle Bin open ("/dev/null", O_RDWR);
Open ("/dev/null", O_RDWR);
Open ("/dev/null", O_RDWR);
else {perror ("fork Error");
Exit (-1); }
}
11.syslog * * Company: XXXX * Author: Rston * Blog: Http://blog.csdn.net/rston * github:https://github.com
/rston * Project: Process relationship and interprocess communication * Features: Demonstrates the use of the Syslog log service. * #include <stdio.h> #include <syslog.h> #include <sys/types.h> #include <unistd.h> #include &l
t;time.h> int main (int argc, char **argv) {printf ("My pid =%d.\n", Getpid ()); Open and syslogd connected channels; The program name is a.out;//If the information cannot be written to log, the information is sent directly to the console;//The information contains the process PID number; The information level is at the normal user level//used in Ubuntu Cat/var /log/syslog View syslog information Openlog ("A.out", Log_cons |
Log_pid, Log_user);
Writes a message to the log log; The information is the prompt information syslog (log_info, "My name is Rston, the time of"%ld.\n ", Time (NULL));
Closed and syslogd connected channel Closelog ();
return 0; }
11.single_run * * Company: XXXX * Author: Rston * Blog: Http://blog.csdn.net/rston * github:https://github
. Com/rston * Project: Process relationship and interprocess communication * functionality: demonstrates the implementation of a single instance run program function. * #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include &
lt;errno.h> #include <stdlib.h> #define PATH "./rstonsinglerun"//Process Exit Function declaration void Delete (void);
int main (int argc, char **argv) {int FD =-1; If the file does not exist, then create, if the file exists, the error FD = open (PATH, O_RDWR | O_creat |
O_EXCL, 0664); if (FD < 0) {if (errno = = eexist) {printf ("The process is now running, Plsest not rep
Eat run process.\n ");
return-1;
}//Register process exit handler function to delete special file atexit (delete);
int i = 0;
For (i=0 i<20; i++) {printf ("I am running now.\n");
Sleep (1);
return 0; Delete special file void Delete (void) {remove (PATH) before the process exits;