Gnu_linux Programming Guide Reading Notes 4 -- Process Control

Source: Internet
Author: User
A Linux Process Model
In the traditional UNIX model, there are two types of operations for ships or modifying processes.
Fork is used to create a new process.
Execve can use another Program To replace the currently running process.

Thread: provides independent execution clues and stack segments, but shares data segments.

2. process attributes
A process is an instance of a running program and is the basic scheduling unit of Linux. A process consists of the following elements:
The current context of the program, which is the current execution status of the program.
Current execution directory of the program
Files And Directories accessed by the program
The trust status or access permissions of a program, such as its file mode and ownership.
Memory and other system resources allocated to processes
1. process ID
Process ID PID
Parent process no. ppid

INIT process 1 is the first process started by the kernel. init guides the system, starts the daemon process, and runs necessary programs. Init is the parent process of all processes.
One common usage of PID is to create a unique file name or directory.
Another typical purpose is to write a PID into a log file as part of a log message.
A process can use its ppid to send signals or messages to its parent process.
Getpid ()
Getppid ();

2 real and valid tive Identification Numbers
<Sys/types. h>
<Unistd. h>

Process ID getpid () pid_t
Parent process ID getppid () pid_t
Real user ID getuid () uid_t
Valid user ID geteuid () uid_t
Real user group ID getgid () gid_t
Valid user group ID getegid () gid_t

3 setuid and setgid
If the real ID and valid ID of a process are different, they are displayed only after the setuid or setgid is set in the running program.
The setuid program and the setgid program are set as the UID or GID of the file because their valid UID or GID is not the UID or GID of the owner or user group that executes the program. The setuid and setgid programs aim to allow users to execute programs with special permissions.

The passwd program is a program with the setuid as the superuser. That is to say, when the program is executed, its valid uid is set as the superuser uid, so that it can modify the/etc/passwd file,

4. User and user group information
There are two ways to convert a uid into a readable name.
The getlogin function returns the login name of the user executing the program. Once a login name exists, it can be passed as a parameter to the getpwname function, this function can return the complete information of a line corresponding to the login name in the/etc/passwd file.

Another way is to pass the UID of the process to the getpwuid () function, which can also return the appropriate entries in the/etc/passwd file.
# Include <unistd. h>
Char * gelogin ();

Returns a pointer containing only strings. The string contains the login name of the user running the process. If this information is not obtained, the function returns NULL.
Once a login name is used, you can call getpwnam to retrieve the UID corresponding to the user name.
# Include <PWD. h>
Struct passwd * getpwnam (const char * Name );

The returned passwd structure Pointer Points to the static allocated memory. The content will be overwritten when getpwnam is called next time.

5. Additional process information
In addition to processes, users, and group IDs, system calls and database functions can also retrieve other attributes of processes, such as resource utilization and execution times.
Wall Clock Time (wall clock time) is the elapsed time
User CPU time (User CPU time) is the process spent in the execution user modeCodeTotal time on
System CPU time is the total amount of time spent on executing kernel code.
This information can be obtained through times or getrusage.
Getrusage
# Include <sys/teimes. h>
Clock_t times (struct TMS * BUF );
Times returns the clock time on the wall. Buf is a pointer to the TMS structure, which stores the time of the current process.

# Include <sys/times. h>
Struct TMS {
Clock_t tms_utime; user CPU time
Clock_t tms_stime; system CPU time
Clock_t tms_cutime; Child's user CPU time
Clock_t tms_cstime; CPU time of the child's System
}

These values are always the number of answers rather than the number of seconds. You can use the sysconf function to convert the number of always answers to the number of seconds.
Long TPS = sysconf (_ SC _clk_tck );
_ SC _clk_tck
It is a macro that defines the number of tick answers per second. The type of sysconf returned value is long, and the program uses it to calculate the number of seconds for a process to run,

When the program calls the system function, it generates a sub-process, and then the sub-process, instead of the parent process, completes all the work and consumes CPU time.
Grep operations are I/O-intensive, not CPU-intensive.

The process resources also include the memory usage of the process, how the memory is organized, the type of Memory Access Mode of the process, the type and quantity of I/O operations performed by the process, and the number of network activities generated by the process. and type.
<Sys/resource. h>
Rusage Structure
Struct rusage
{
Struct timeval ru_utime; // time when the user mode code is executed
Struct timeval ru_sutime; // time when the kernel code is executed
Long ru_maxrss;
Long ru_maxixrss;
Long ru_maxidrss
Long ru_maxisrss;
Long ru_minflt // Number of secondary failures (disk access is not caused by memory access)
Long ru_majflt; // Number of primary failures (disk access caused by memory access)
Long ru_nswap; // Number of memory pages read from the disk due to major errors
Long ru_inblock;
Long ru_outblock;
Long ru_msgsnd;
Long ru_msgrcv;
Long ru_nsiquals;
Long ru_nvcsw;
Long ru_nivcsw;
}

# Include <sys/times. h>
# Include <sys/resource. h>
# Include <unistd. h>
Int getrusage (INT who, struct rusage * usage );
WHO:
Rusage_self
Rusage_children

6 sessions and Process Groups
A process group is the geometry of related processes. These processes are generally the command sequences in a pipeline.
All processes in the process group have the same process group number, namely, pgid.

A session is composed of one or more process groups. A session leader process is a process that creates a session. Each painting has a unique ID and becomes a session ID. It is only the pid of the session leader process. The role of a session on a process group is the same as that of a process group on a single process.

Creation process:
7. Use the system function
System sends the command/bin/sh-C to run the string. The string can contain options and parameters, and the entire command line is then passed to the system to call execve. If/bin/sh is not found, system returns 127
# Include <stdlib. h>
INT system (const char * string );

# Include <stdio. h>
Void perror (const char * s );
Perror () is used to output the cause of the previous function error to the standard error (stderr ). The string referred to by parameter S is printed first, followed by the error cause string. The cause of this error is determined based on the value of the global variable errno.

8 fork system call
# Include <unistd. h>
Pid_t fork (void );
If fork runs successfully, it returns the PID of the child process to the parent process, and returns 0 to the child process. This means that even if you only call the Um fork once, it can return twice.

The new process created by fork is the same as the parent process.

The child process does not inherit the timeout settings of the parent process, the file lock created by the parent process, or the pending signal.

Fork's asynchronous behavior means that the code of the parent process cannot be executed in the child process.

Exec function family
Int execl (const char * path, const char * Arg ,.....);
Int execlp (const char * file, const char * Arg ,.....);
Int execle (const char * path, const char * Arg, char * const envp []);

Int execv (const char * path, const char * const argv []);
Int execve (const char * path, const char * const argv [], char * const envp []);
Int execvp (const char * file, char * const argv []);

Execve accepts three parameters: path, argv, and envp. PATH is the complete path of the binary file or script to be executed.
Argv is the complete list of parameters to be passed to the program, including argv [0]. It is generally the name of the execution program.
Envp is a dedicated environment pointer that only needs to be used to execed the execed program.

The three functions whose names contain l want to receive a list of parameters separated by commas (,). The list uses a null pointer as the end sign. These parameters are sent to the program to be executed.
However, the function whose name contains v accepts a vector, that is, a pointer array pointing to a string ending with null.

Two execve execle functions ending with E allow you to create a special environment for the program to be executed, which is saved in envp, it is also a pointer to a string array ending with null. Each string in the array is also a pointer to a string array ending with null. Each string in the array also ends with null. Each string is in the form of "name = value", name is the name of the environment variable, and value is the value.
For example
Char * envp [] = {"Path =/bin:/usr/bin", "USR = joeblow", null };
The other four functions implicitly accept their environment through the global variable environ

Putenv and getenv can be used to manipulate the environment inherited by these functions.
# Include <stdlib. h>
Int putenv (cosnt char * string );
Char * getenv (const char * Name );
Char envval [] = {"mypath =/usr/local/someapp/bin "};
Putenv (envval );
Getenv ("mypath ");

9 popen Function
Popen uses pipelines to work
# Include <stdio. h>
File * popen (const char * conmmand, const char * type );
Int pclose (File * stream );

10 waiting process-Wait function family
Zombie process: child process terminated before the parent process has the opportunity to use the wait or waitpid mobile phone to exit the status.
You can call wait or waitpid to collect the exit status of sub-processes.
# Include <sys/Wait. H>
# Include <sys/types. h>
Pid_t wait (int * status );
Pid_t waitpid (pid_t PID, int * status, int options );
Status stores the exit status of the sub-process. The PID is the PID of the waiting process. Valid value:
-1. Wait for any sub-process whose pgid is equal to the absolute value of the PID.
1. Wait for any sub-process
0 wait for any child process whose pgid is equal to the call Process
0: Wait for the sub-process with PID equal to PID

Options:
Wnohang. If no sub-process exits, return immediately.
Wuntraced should be returned because there are no reporting processes.

11. Killing programs
A process is terminated for one of the following five reasons:
Its main function calls return
It calls exit
It calls _ exit
It calls abort
It is terminated by a signal

Exit causes the program to terminate normally and returns the status of the parent process. Functions registered with atexit are also executed.
_ Exit: Terminate the process that calls it immediately. Functions registered with atexit are not executed.

# Include <stdlib. h>
Void abort (void );

One process can use the kill function to kill another process.
# Include <signal. h>
# Include <sys/types. h>
Int kill (pid_t PID, int sig );

PID specifies the process to be killed, and SIG is the signal to be sent.

12 signal
A signal is an event transmitted to a process by the same or different processes. A signal is usually used to notify a process of an exception event.
Each signal starts with SIG. These names correspond to Positive Integer constants and become semaphores <signal. h>

When a process receives a signal, it can take one of the following three measures for the signal:
Ignore this signal
Capture this signal, which will lead to the execution of a piece of code that becomes a signal processor, which is called a processing signal
Allows default signal operations

The signal set is a C data type sigset_t <signal. h>

Sending signal:
From a programming perspective, there are two methods to send signals to a running program: using the kill command and using the kill function.
Kill can be used to send signals other than killing a process (sigkill, sigtrem, sigquit.

Each process can determine how to respond to all signals except sigstop and sigkill, and these two signals cannot be captured or ignored. The easiest way to capture a signal is not to actually capture the signal, but to wait for them to be sent. The alarm function sets a timer to send sigalrm signals when the timer time is reached. The pause function also provides similar functions, but it suspends the process until it receives any signal.

# Include <unistd. h>
Unsigned int alarm (unisgned int seconds );
Seconds is the number of seconds from the timer time to the clock. If no other timeout value is set, the return value is 0. Otherwise, the return value is the number of seconds retained during the timeout period. A process can only set a timeout value once. Setting seconds to 0 will cancel the preceding settings.

# Include <unistd. h>
Int pause ();
Pause returns the call process only when the process captures a signal.

Create a signal set ---- set the signal to be captured ------ register a signal processor with the kernel ---- Wait for the signal to be captured

Define a Signal Processor
Int sigemptyset (sigset_t * Set );
Int sigfillset (sigset_t * Set );
Int sigaddset (sigset_t * Set, int SIGNUM );
Int sigdelset (sigset_t * Set, int SIGNUM );
Int sigismember (const sigset_t * Set, int SIGNUM );
Set is a set of sigset_t signals. Sigemptyset initializes the signal set to retrieve all signals from the set. Sigfillset initializes the signal set, which contains all signals. Sigaddset adds the signal SIGNUM to the signal set. The sigdelset removes the SIGNUM signal from the ry.

Create a Signal Set
Use sigemptyset or sigfillset to initialize a signal set. If you create an empty signal set, you need to use sigaddset to add signals to the collection you are interested in. If a full signal set is created, use sigdelset to delete the signal from the signal mask.
Sigset_t newset;
Sigemptyset (& newset); // create an empty Signal Set
Sigaddset (& newset, sigchld); // Add a signal to the Signal Set
Sigismember (& newset, sigchld); // check whether a specified signal exists in the Signal Set

Register a Signal Processor
Sigprocmask: set or modify the current signal mask
Sigaction call registers a signal processor as a signal or signal to be captured
# Include <signal. h>
Int sigprocmask (INT how, const sigset_t * Set, sigset_t * oldset );
How:
Sig_block set contains other signals to be blocked
The sig_unblock set contains the signal to be blocked.
Sig_setmask set contains the new signal mask
Null, ignored
If set is null, the current mask is saved in oldset. If oldset is null, it is ignored.
# Include <signal. h>
Int sigaction (int signum, const struct sigaction * Act, struct sigaction * oldact );
Sigaction sets the signal processor for the signal specified by SIGNUM. The sigaction Structure describes the signal deployment.
Struct sigaction {
Void (* sa_hundler) (INT );
Sigset_t sa_mask;
Int sa_flags;
Void (* sa_hundler) (void );
}
Sa_handler is the function pointer, which specifies the processor or function to be called after the signal in SIGNUM is generated.
Or
Sig_dfl SIGNUM default action
Sig_ign ignores the SIGNUM Signal

13 Detection Signal
# Include <signal. h>
Int sigpending (sigset_t * Set );
The set of pending signals is returned in set.

14 process scheduling
# include
# include
# include
# include
int sched_setcheduler (pid_t PID, int policy, const struct sched_param * P);
int sched_get_prority_max (INT policy );
int sched_get_prority_min (INT policy);
int getprority (INT which, int who);
int setprority (INT which, int who, int PRIO );
int nice (INT Inc);

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.