Information Security system design basics 11th Week Study summary-20135227 Huang

Source: Internet
Author: User
Tags signal handler sleep function terminates

Section 8 Chapters Exception Control Flow

Control Flow: Controls the transfer sequence.

Control transfer: From an instruction to the next instruction.

Exception control Flow: The modern operating system responds to the system state by causing mutations in the control flow, known as abnormal control flows.

First, abnormal

1 , the anatomy of the exception , as shown in:

Exception: A mutation in the control flow that responds to certain changes in the state of the processor.

Icurr: Current Instruction

Events: State changes

2 , exception handling

Exception table: When the processor detects that an event occurs, it makes an indirect procedure call (exception) to the exception handler through the Jump table.

Exception number: One of the possible types of exceptions in the system is assigned an exception number that is a unique nonnegative integer. The exception number is the index to the exception table.

Exceptions are similar to procedure calls, but there are some important differences.

Once the hardware has triggered an exception, the exception handler is completed by the software.

3 , category of exceptions-- interrupts, traps, failures, and terminations

A) Interrupt handling: Asynchronous means that a hardware interrupt is not caused by any instruction, but by an event of an external I/O device.

b) Traps and system calls: System calls are encapsulated functions that are internally implemented by instruction Int N.

The most important use of traps is to provide system calls. System calls run in kernel mode and can access stacks in the kernel.

The parameters of the system call are passed through a generic register instead of a stack, such as the%EAX storage system call number,%EBX,%ECX,%EDX,%ESI,%EDI,%EBP stores up to six parameters,%esp is not available, because it is overwritten after entering kernel mode.

c) Failure

d) Termination

Ii. process

(Operating system layer): logical control flow, private address space, multitasking, concurrency, parallelism, context, context switching, scheduling.

A process is an executing instance of a program. Each program in the system is running in the context of a process.

The key abstraction that a process provides to an application: a) A separate logical control flow; b) a private address space

1 , logical control Flow

The sequence of program counter (PC) values is called logical control flow, or logical flow. As shown, a physical control flow of the processor is divided into three logical streams, one per process.

Some concepts: Concurrent flow: Concurrent flow the execution of one logical stream overlaps the other stream in time.

Concurrency: The general phenomenon of concurrent execution of multiple streams is called concurrency.

Multitasking: Multiple processes concurrency is called multitasking.

Parallel: Concurrent streams on different CPUs or computers

2 , private address space

A process provides its own private address space for each program.

The process that runs the application code is initially in user mode. The only way the process changes from user mode to kernel mode is through exceptions.

Linux provides the/proc file system, which allows the user-mode process to access the contents of the kernel data structure.

3 , context switching, scheduling

Context switching: The operating system kernel uses exception control flows called context switches to achieve multitasking.

Context Switch: A) Saves the context of the current process; b) Restores the context in which a previously preempted process was saved; c) passes control to the newly restored process

Dispatch: The scheduler in the kernel implements scheduling.

Context switching may occur when the kernel performs context switching on behalf of the user. If a system call is blocked, the kernel can let the current process hibernate and switch to another process, such as a read system call, or sleep will display a request for the calling process to hibernate. In general, the kernel can also determine context switching, rather than returning control to the calling process, even if the system call is not blocked.

Interrupts can also cause context switching. For example, the timer is interrupted.

4 , Process Control

Get process ID:

Create and Terminate processes: three states of a process-run, stop, and terminate. The process terminates the process for three reasons: it receives a signal, the signal terminates the process by default, and the Exit function is called from the main program.

The parent process creates a new run child process by calling Fork: The parent process has the same (but separate) address space as the child process and has the same set of file-defying characters.

To reclaim a child process:

Recycle: When a process terminates, the kernel does not immediately purge it from the system. Instead, the process is kept in a state that has been terminated until it is reclaimed by its parent process.

Zombie Process: A process that has been terminated but not yet reclaimed is called a zombie process.

Two ways to reclaim a child process: 1, init process 2 for the kernel, parent process waitpid function

1) If the parent process does not reclaim its zombie process, then the kernel will schedule init to go to town to reclaim it. The PID of the Init process is 1 and is created when the system is initialized.

2) A process can wait for its child process to terminate or stop by calling the Waitpid function.

The Waitpid function is somewhat complex, and by default (when options=0), waitpid suspends execution of the calling process, knowing that it waits for a child process in the collection to terminate.

    1. Determining the members of a waiting set
    2. Modify default behavior
    3. Check the exit status of the reclaimed child process
    4. Error condition

Wait function:

Wait (&status) function, equivalent to calling Wait ( -1,&status,0)

Let the process hibernate:

The sleep function suspends a process for a specified amount of time.

The pause function lets the calling function hibernate, knowing that the process receives a signal.

Load and run the program:

Environment array operation function:

Third, the signal

(between the operating system and the application): signal transfer between processes

A higher-level form of software exception, called a UNIX signal, allows a process to interrupt other processes.

Low-level hardware exceptions are handled by the kernel exception handlers, which are normally not visible to the user process. The signal provides a mechanism to inform the user that the process has occurred with these exceptions.

1 , signal processing process

1) Send a signal: The kernel sends a signal to the destination process by updating a state in the context of the destination process. There are two reasons for sending a signal: a) The kernel detects a system event; b) a process calls the KILL function and sends a signal

2) receive the signal: The destination process receives the signal. The process can ignore this signal, terminate it, or capture the signal by executing a signal processing program.

Note: The signal to be processed, a type of signal can only have a pending signal, the excess will not queue, but will be shed; The signal can also be blocked.

2 , send signal:/bin/kill, kill function, keyboard, alarm function

Process group: Each process belongs to only one process group, and the process group is identified by a process group ID. By default, a child process and its parent process belong to a process group.

At any time, there is at most one foreground job and 0 or more background jobs. The shell creates a separate process group for each job, and one job corresponds to a process group.

Send signal with kill function: Send Sigkill signal

Send signal with alarm function: Send Sogalarm signal

3 , receiving signal

The process can modify the default behavior associated with the signal by using the signal function. The only exceptions are sigstop and Sigkill, whose default behavior cannot be modified.

4 , signal processing problems

When a program captures multiple signals, it is easy to have some wise problems:

    1. Pending signals are not queued for processing
    2. Pending signal is blocked
    3. System call is interrupted

Examples of programs:

The defect procedure is as follows:

The output is as follows:

      

As can be seen from the output, although 3 sigchild signals were sent, only two signals were accepted. The reason is that the 3~12 line program, each child process end, can trigger a signal; The function call only processes one sigchild signal at a time.

The modified program is as follows:

3~14 line program, although still a sub-process to the end of a signal, single the function through the loop, as much as possible to deal with multiple sigchild signals, and 34~36 line, to prevent system calls are interrupted, manually start the system call.

5 , Portable signal processing: The purpose is to unify the semantics of the same signal in the non-pass system. The Sigaction function, or its wrapper function, is the signal function.

6 , display ground blocking and unblocking functions

7 , synchronizing streams to avoid concurrency errors

The question of how to write concurrent streaming programs that read and write to the same storage location has plagued generations of computer scientists.

For example, the issue of competition. Examples of the program are:

Workaround as shown in the program shown, block the SIGCHLD signal (19~22 line) before calling Fork, and then unblock the signal (25 rows) after we call AddJob, we guarantee that the child process will be recycled after it is added to the job list. Note that the child process inherits the blocked signal from their parent process, so we must carefully touch the SIGCHLD signal (31 rows) that is blocked in the child process before calling Execve (this is because the child process inherits the set of blocked signals from the parent process, but this is a two different collection, they do not share memory).

Four, non-local jump (application layer)

The C language provides a form of user-level exception control flow called a local jump. Provided through the setjmp and LONGJMP functions.

      

The SETJMP function is called only once, but is returned multiple times: once when setjmp is first called and the calling environment is saved in the buffer env, once for each corresponding longjmp call. On the other hand, longjmp is called only once, but never returned. The sig-function is a version of the setjmp and LONGJMP functions that can be used by a signal handler.

An important application of non-local jumps is to allow immediate return from a deeply nested function call, usually caused by an error condition being detected. Examples are as follows:

Another important application of non-local jumps is to have a signal handler branch to a special code location instead of returning to the location of the command that was interrupted. Examples are as follows:

The program output is as follows:

Additional:

Piping Pipe function

One example of using process communication is the pipeline communication for UNIX systems. Unix systems, starting with system V, provide two ways to communicate with well-known pipes and nameless pipes, and the nameless pipes are described here.

The nameless pipe provides a communication pipeline that transmits messages in a bitstream way for the process of establishing the pipeline and its descendants. The pipeline is logically viewed as a pipe file, which is physically composed of a file system's high-speed buffer area and rarely starts peripherals. The sending process takes advantage of the file system's system call to write (fd[1],buf,size), buf a message of length size to the pipe entry fd[1], and the receiving process uses the system call read (Fd[0],buf,size) from the pipe outlet fd[0] Exports the message that reads the size character into the BUF. Here, the pipeline transmits the message in FIFO (first-in, in-place) mode, and only one-way messages

Using a UNIX-provided system to call the pipe, a synchronous communication pipeline can be established. The format is:

int fd[2];

Pipe (FD)

Here, Fd[1] is the write end, fd[0] is the read-out end.

I/O REDIRECT dup,dup2

DUP and dup2 are also two very useful calls that are used to copy the descriptor of a file. They are often used to redirect stdin, stdout, and stderr of processes. The prototypes of these two functions are as follows:

C code

#include <unistd.h>

int dup (int oldfd);

int dup2 (int oldfd, int targetfd);

DUP () function

With the function DUP, we can copy a descriptor. Passed to the function an existing descriptor, it will return a new descriptor, the new descriptor is a copy of the descriptor passed to it. This means that both descriptors share the same data structure. For example, if we perform a lseek operation on a file descriptor, the location of the first file is the same as the second one. Here is a snippet of code to illustrate how the DUP function is used:

C code

int fd1, FD2;

...

FD2 = DUP (FD1);

It is important to note that we can create a descriptor before calling fork, which is the same as invoking the DUP to create a descriptor, and the child process will also receive a copy of the descriptor.

dup2 () function

The DUP2 function is similar to the DUP function, but the DUP2 function allows the caller to specify the ID of a valid descriptor and a target descriptor. When the DUP2 function returns successfully, the target descriptor (the second argument of the Dup2 function) becomes a copy of the source descriptor (the first parameter of the DUP2 function), in other words, the two file descriptor now points to the same file and is the file to which the function's first argument points. Let's illustrate this in a piece of code:

C code

int OLDFD;

OLDFD = open ("App_log", (O_rdwr | o_create), 0644);

Dup2 (OLDFD, 1);

Close (OLDFD);

In this example, we open a new file called "App_log" and receive a file descriptor called FD1. We call the DUP2 function with the arguments OLDFD and 1, which causes the file descriptor represented by 1 to be replaced with our newly opened file descriptor (that is, stdout, because the standard output file has an ID of 1). Anything written to StdOut will now be written to a file named "App_log". Note that the DUP2 function immediately closes the OLDFD after it has been copied, but does not close the newly opened file descriptor because the file Descriptor 1 now also points to it.

Example

Let's introduce a more in-depth example code. Recalling the command line pipeline, we can connect the standard output of the Ls–l command to the WC–L command as standard input. Next, we will use a C program to illustrate the implementation of this process. The code is shown below.

C code

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

int main ()

{

int pfds[2];

if (pipe (pfds) = = 0) {

if (fork () = = 0) {

Close (1);

Dup2 (Pfds[1], 1);

Close (Pfds[0]);

EXECLP ("ls", "ls", "-l", NULL);

} else {

Close (0);

Dup2 (Pfds[0], 0);

Close (pfds[1]);

EXECLP ("WC", "WC", "-l", NULL);

}

return 0;

}

In the sample code, you first establish a pipeline in line 9th, and then divide the application into two processes: a child process (13–16) and a parent process (line 20–23). Next, the STDOUT descriptor (line 13th) is closed first in the subprocess, and then the LS–L command function is provided, but it is not written to stdout (line 13th), but rather to the output of the pipeline we created, which is done via the DUP2 function to redirect. In line 14th, use the Dup2 function to redirect stdout to the pipeline (Pfds[1]). After that, turn off the input of the pipe immediately. Then, using the EXECLP function to replace the image of the process with the process image of the command ls–l, any output of it will be sent to the input side of the pipeline once the command executes.

Now let's look at the receiving end of the pipe. As you can see from the code, the receiving side of the pipeline is assumed by the parent process. First close the stdin descriptor (line 20th), because we do not receive data input from standard device files such as the machine's keyboard, but instead receive data from the output of other programs. Then, once again, using the DUP2 function (line 21st), let the input of the pipeline be input, which is achieved by redirecting the file descriptor 0 (that is, the regular stdin) to Pfds[0]. Close the stdout end of the pipe (pfds[1]) because it is not available here. Finally, using the EXECLP function to replace the image of the parent process with the process image of the command wc-l, the command wc-l the contents of the pipeline as its input (line 23rd).

Summarize:

This chapter reads more, but the key content is not many, mainly is mastering the process and its control function use, the signal sends the function, the reception function and the processing function. The most rewarding part of the learning process in this chapter is the understanding of the general concept of the process, which is learning the process scheduling mechanism recently, allowing me to supplement the vacancy on the process.

Resources:

"In-depth understanding of computer Systems" Chapter 8th, chapter 10th I/O redirection

Pipe pipe:http://blog.csdn.net/thinkinwm/article/details/8710857

dup,dup2 function: http://eriol.iteye.com/blog/1180624

Information Security system design basics 11th Week Study summary-20135227 Huang

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.