[IT goose C/C + + Series Courses] pretty boy, I want to learn programming. Why tell me about the operating system?

Day01:
Let's regain our love for our dream lover C and C + +
[IT C/C + + Series Courses] Operating System Fundamentals Course

A "shuangwen" programming tutorial of "against the sky"


BILIBILI IT goose BILIBILI@IT goose

Course introduction:

[C/C + + Series Courses] Operating System Fundamentals Course
This course uses ICS and SP teaching mode to explain the boring C/C + + in easy to understand language. This course will affect the performance and correctness of application programs from hardware, operating system and compiling system. SP is a system programming course. When we have basic coding skills, the course will briefly introduce system programming (Linux), process, network programming and so on.

preface:

There are many unsatisfactory points in the article. I hope scholars and friends can make corrections and suggestions. I am very grateful!

Mainstream operating system OS

Mainstream operating systems include windows, MacOS, Android, Linux, etc. strictly speaking, Android system belongs to the branch of Linux system. Android system is based on Linux system kernel, and mainstream Ubuntu Debian distribution versions are also based on Linux Kernel, but different versions of Linux distribution versions have different software sources, which is one of the reasons why Linux distribution versions are different. However, Linux system has a community where developers all over the world can report to kernl Org submits its contribution to the kernel and high-level vulnerabilities related to Linux system. Windows and MacOS are operating systems designed based on Unix.

🤔 [question 1]
What is the relationship between Android system and Linux system?

Android is based on the Linux kernel, which provides core services: security, memory management, process management, network and driver model.

Some shell s may belong to the Android system, not the kernel.
What is a shell? Students may have seen this word in the anti day hacker novel. A hacker is a shell. The Chinese translation of shell refers to the command interpreter of human machine interaction. In short, in windows system, cmd belongs to shell, bash on Linux belongs to shell, Terminal terminal Terminal on MacOS, and what is bash (in short, the so-called forcing command entered by a hacker in the computer black window, the following figure is a screenshot of the Terminal)
Simple installation command:

echo Special for pretty boy shell
echo Hello, pretty boy

🤔 This is also programming??? To be exact, this is the language that the shell can understand.

what ⬆️ This is the shell?!

From Manchester machine age to mini computer age

Large machine age

The earliest computers were mainframes without any form of operating system. 1949. The original machine was the Manchester 1 commercial computer, which was one of the earliest stored program computers. Each user used the machine alone within a predetermined period of time and arrived at the computer with programs and data, usually perforated paper cards and magnetic tapes or paper tapes. The program will be loaded into the machine and the machine will be set to work until the program is completed or crashes. The program can usually be debugged through the control panel using turntable, toggle switch and panel light.

Later, the machine introduced a code base to help the program input and output work. What is a code base
Generally refers to the source code file written manually, but the machine can only perform a task once at a time.

Mini computer era

UNIX operating system was developed by Bell Labs of at & T company in 1960. It is a system written in C language. How UNIX works is not introduced in detail in this paper. But you need to understand that UNIX operating system is an epoch-making product. Because C language has the characteristics of portability, UNIX can be transplanted on different hardware devices.
(add the history of C language: I have learned the basic overview of C language from the above Let's regain our love for our dream lover C and C + +)
C language was designed and developed by Dennis rich and Ken Thompson in Bell labs based on B language in order to transplant and develop UNIX operating system from 1969 to 1973.

The era after Apple and DOS

The development of microprocessors has popularized the application of computers to small and medium-sized enterprises and personal enthusiasts. The popularity of computers promotes the development of common interfaces of hardware components. The main CPU used in the early computer is the cp-80 / 80-80-80. These computers have a small boot program in ROM (read only memory), which can load the operating system from disk to memory. The BIOS of IBM-PC series is an extension of this idea. Since the birth of the first IBM-PC in 1981, the function of BIOS has been continuously enhanced.

Back to the focus of this article, we have * * [question 2] 🤔 ️**
How did the original operating system migrate to the computer?

For historical knowledge of operating system, please refer to: RedHat code hero Linux China

Modern operating system

Operating System Internals and Design Principles

Operating system outline:

Kernel:

Kernel system architecture:

Exokernel external core * * Hybrid Kernel hybrid kernel & micro kernel Microkernel, μ- Kernel macro kernel Unikernel**

Kernel components

The driver can load the core module LKM (Loadable kernel module), Micro Kernel and User Space

Concept:
Content switch: multitask processing multitasking interrupt processing interrupt task switching between user mode and kernel mode user mode switch to kernel mode
Interrupt: interrupt, as the name suggests, when our computer hardware or OS receives a special signal, the computer will immediately stop the work in hand and do another thing. After completing the task, continue to do the task in hand. For example, when you are studying, your good brother asks you to go out and play badminton. After playing badminton, you have to start the learning journey. This definition is not professional, but we can understand it so easily.
Be professional (key points):
Hardware Interrupt
Software Interrupt
Since the soft interrupt instruction usually runs a subroutine that switches the CPU to the kernel mode (Kernel Mode/Ring 0), it is often used to implement the System call

Interprocess communication

IPC (inter process communication) refers to some technologies or methods of transmitting data or signals between at least two processes or threads. A process is the smallest unit of resources allocated by a computer system (strictly speaking, a thread) Each process has its own part of independent system resources, which are isolated from each other. In order to enable different processes to access resources and coordinate with each other, there is interprocess communication.

IPC communication application: Web server. We use process communication to share web files (html) through web pages

Process

I want to command the computer. At this time, the operating system will produce processes. The same program can produce multiple processes (one to many relationship). The running efficiency of the process depends on the running efficiency of the CPU.
Key points: the difference between process and thread: process is a way for the computer to manage the incoming program. A process can contain one or more threads. A thread can be understood as a child process. Threads are a subset of processes.

Process Control Block (PCB)

it included process status, it can be new, ready, running, waiting and blocked and so on.
(I don't know why there are so many foreign languages here. Students understand that computers speak more clearly in foreign languages.) CPU register (accumulator), indexer, stack pointer

Pretty boy, wait, what is Stack Pointer? It's a deja vu name. Yes, Stack Pointer is very important! Here is a brief introduction to stack pointers. (boring stack pointers can be used frequently in the future)

Important ADT in computer:

ADT: Abstract Data Type
This section takes you through the stack

Stack, commonly known as stack, Pinyin alphabet (zhan), the "stack" of the inn.

There are two basic stack operations: (push) and (pop)
Features: first in first out, last in first out.
In C language, we use a data structure called linked list to describe it. Please observe the figure below and describe the characteristics

Stack can be implemented in two ways: array and linked list.
The following program comes from Gao Yifan's algorithm implementation and analysis of data structure, 2nd Edition, October 2004
Storage structure:

#define STACK_INIT_SIZE 10 / * initial allocation of storage space*/
#define STACK_INCREMENT 2 / * storage space allocation increment*/
typedef struct SqStack
{
	SElemType *base; /* The value of base is NULL before stack construction and after stack destruction */
	SElemType *top; /* Stack top pointer */
	int stacksize; /* Currently allocated storage space, in elements */
}SqStack; /* Sequential stack */

basic operation

/* bo3-1.c Basic operations of sequential stack (storage structure defined by c3-1.h) (9) */
void InitStack(SqStack *S)
{	/* Construct an empty stack S */
	(*S).base=(SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
	if(!(*S).base)
		exit(OVERFLOW); /* Storage allocation failed */
	(*S).top=(*S).base;
	(*S).stacksize=STACK_INIT_SIZE;
}

void DestroyStack(SqStack *S)
{	/* Destroy stack S, S no longer exists */
	free((*S).base);
	(*S).base=NULL;
	(*S).top=NULL;
	(*S).stacksize=0;
}

void ClearStack(SqStack *S)
{	/* Set S to empty stack */
	(*S).top=(*S).base;
}

Status StackEmpty(SqStack S)
{	/* If stack S is an empty stack, it returns TRUE; otherwise, it returns FALSE */
	if(S.top==S.base)
		return TRUE;
	else
		return FALSE;
}

int StackLength(SqStack S)
{	/* Returns the number of elements of S, that is, the length of the stack */
	return S.top-S.base;
}

Status GetTop(SqStack S,SElemType *e)
{ /* If the stack is not empty, use e to return the top element of S and return OK; Otherwise, ERROR is returned */
	if(S.top>S.base)
	{
		*e=*(S.top-1);
		return OK;
	}
	else
		return ERROR;
}

void Push(SqStack *S,SElemType e)
{	/* Insert element e as the new stack top element */
	if((*S).top-(*S).base>=(*S).stacksize) /* Stack full, additional storage space */
	{
		(*S).base=(SElemType *)realloc((*S).base,((*S).stacksize+STACK_INCREMENT)*sizeof(SElemType));
		if(!(*S).base)
			exit(OVERFLOW); /* Storage allocation failed */
		(*S).top=(*S).base+(*S).stacksize;
		(*S).stacksize+=STACK_INCREMENT;
	}
	*((*S).top)++=e;
}

Status Pop(SqStack *S,SElemType *e)
{	/* If the stack is not empty, delete the top element of S, return its value with e, and return OK; Otherwise, ERROR is returned */
	if((*S).top==(*S).base)
		return ERROR;
	*e=*--(*S).top;
		return OK;
}

void StackTraverse(SqStack S,void(*visit)(SElemType))
{	/* From the bottom of the stack to the top of the stack, call the function visit() for each element in the stack in turn */
	while(S.top>S.base)
		visit(*S.base++);
	printf("\n");
}

Basic operation of linked list

/* bo2-8.c Some basic operations of single linked list without leading node (storage structure defined by c2-2.h) (9) */
#Define destroylist / * the operations of destroylist() and ClearList() are the same*/
void InitList(LinkList *L)
{	/* Operation result: construct an empty linear table L */
	*L=NULL; /* The pointer is null */
}

void ClearList(LinkList *L)
{	/* Initial condition: linear table L already exists. Operation result: reset L to empty table */
	LinkList p;
	while(*L) /* L Not empty */
	{
		p=*L; /* p Point to initial node */
		*L=(*L)->next; /* L Point to the second node (new initial node) */
		free(p); /* Release initial node */
	}
}

Status ListEmpty(LinkList L)
{	/* Initial condition: linear table L already exists. Operation result: if L is an empty table, it returns TRUE; otherwise, it returns FALSE */
	if(L)
		return FALSE;
	else
		return TRUE;
}

int ListLength(LinkList L)
{	/* Initial condition: linear table l already exists. Operation result: returns the number of data elements in L */
	int i=0;
	LinkList p=L;
	while(p) /* p Point to the node (not to the end of the table) */
	{
		p=p->next; /* p Point to the next node */
		i++;
	}
	return i;
}

Status GetElem(LinkList L,int i,ElemType *e)
{	/* L Is the header pointer of the single linked list without the leading node. When the ith element exists, its value is assigned to e and returns OK; otherwise, it returns ERROR */
	int j=1;
	LinkList p=L;
	if(i<1) /* i Illegal value */
		return ERROR;
	while(j<i&&p) /* Not to the i-th element, not to the end of the table */
	{
		j++;
		p=p->next;
	}
	if(j==i) /* The ith element exists */
	{
		*e=p->data;
		return OK;
	}
	else
		return ERROR;
}

int LocateElem(LinkList L,ElemType e,Status(*compare)(ElemType,ElemType))
{ 	/* Initial condition: linear table L already exists, compare() is the data element determination function (1 if satisfied, otherwise 0) */
	/* Operation result: returns the bit order of the first data element in L that satisfies the relationship compare() with e. */
	/*           If such a data element does not exist, the return value is 0 */
	int i=0;
	LinkList p=L;
	while(p)
	{
		i++;
		if(compare(p->data,e)) /* Find such a data element */
		return i;
		p=p->next;
	}
	return 0;
}

Status ListInsert(LinkList *L,int i,ElemType e)
{	/* Insert the element e before the ith position in the single chain linear table L without the leading node */
	int j=1;
	LinkList p=*L,s;
	if(i<1) /* i Illegal value */
		return ERROR;
	s=(LinkList)malloc(sizeof(struct LNode)); /* Generate new node */
	s->data=e; /* Assign a value to the data field of s */
	if(i==1) /* Insert in header */
	{
		s->next=*L;
		*L=s; /* Change L */
	}
	else
	{	/* Insert in the rest of the table */
		while(p&&j<i-1) /* Find the i-1 node */
		{
			p=p->next;
			j++;
		}
		if(!p) /* i Greater than meter length + 1 */
			return ERROR;
		s->next=p->next;
		p->next=s;
	}
	return OK;
}

Status ListDelete(LinkList *L,int i,ElemType *e)
{	/* In the single chain linear table L without the leading node, delete the ith element and return its value by e */
	int j=1;
	LinkList p=*L,q;
	if(i==1) /* Delete the first node */
	{
		*L=p->next; /* L Start with the second node */
		*e=p->data;
		free(p); /* Delete and release the first node */
	}
	else
	{
		while(p->next&&j<i-1) /* Find the ith node and point p to its precursor */
		{
			p=p->next;
			j++;
		}
		if(!p->next||j>i-1) /* Unreasonable deletion position */
			return ERROR;
		q=p->next; /* Delete and release nodes */
		p->next=q->next;
		*e=q->data;
		free(q);
	}
	return OK;
}

void ListTraverse(LinkList L,void(*vi)(ElemType))
{	/* Initial condition: linear table l already exists. Operation result: call the function vi() for each data element of L in turn */
	LinkList p=L;
	while(p)
	{
		vi(p->data);
		p=p->next;
	}
	printf("\n");
}

Back to the introduction of process management.
Real time operating system (RTOS)

Compared with the general operating system, the biggest feature of real-time operating system is "real-time" If a task needs to be executed, the real-time operating system will execute the task immediately (in a short time) without a long delay. This characteristic ensures the timely execution of various tasks.

Thread:

Thread is the smallest unit that the operating system can schedule operations. In most cases, it is included in the process and is the actual operation unit in the process. A thread refers to a single sequential control flow in a process. Multiple threads can be concurrent in a process, and each thread executes different tasks in parallel. In Unix System V and SunOS, it is also called lightweight processes, but lightweight processes refer more to kernel thread s and user thread s to threads.

C++11 standard creation thread:
(students here don't know much about C++11. You can go to my station B video or the previous article)

Introduction to C++11 standard thread:

On August 12, 2011, the international organization for Standardization (ISO) released the ISO C + + standard. C++11 introduced C + + standard threads for the first time. VS2012 running on Windows platform and g++4.7 running on Linux platform perfectly support C++11 threads.
thread is a file header
Creating thread implementation prototype with C++11

std::thread::thread(Function&& f, Args&&... args);

Wait for the thread to end:

std::thread::join();

Out of thread control:

std::thread::detach();

Swap thread:

std::thread::swap(thread& other);

C++11 correlation function:
Create thread:

int thrd_create(thrd_t *thr, thrd_start_t func, void *arg);

End this thread:

_Noreturn void thrd_exit( int res );

Wait for the thread to finish running:

int thrd_join(thrd_t thr, int *res);

Returns the thread identifier of the current thread:

thrd_t thrd_current();

(tu) Cao: java thread (Java means many nouns)
1. The run() method of thread / runnable is terminated after running.
2. Use the cancel() method of the Future class to call.
3. Call the shutdown() and shutdown now () methods of the thread pool
4. The daemon thread will automatically terminate when all non daemon threads end.
Time sharing system

Time sharing system is a way of sharing resources in computer science. It uses multi-channel programs and multi task processing to enable multiple users to use a computer at the same time.

This series of courses follows the signature - non-commercial use 3.0 Chinese Mainland (CC BY-NC 3.0 CN)
Please indicate CSDN @IT for reprint

Last words:

I believe that after this class, you have learned many strange nouns and have more doubts. This is normal, because this class combs the operating system. So do you have a passion for computer learning in your mind? Do you have a new view on OS? Everyone has their own answer in their heart.

⛽ ️ ⛽ ️ ⛽ (Penguin forced to take the road of traffic ~ ~ ~) handsome boy, pay attention ➕ Go again ⛽ ️ ⛽ ️ ⛽ ️

Tags: Python Java C C++ Linux

Posted by PHPcoder25 on Sun, 15 May 2022 00:51:08 +0300