Several concepts that must be understood in Linux environment programming
For beginners, if they want to program in a Linux environment, they must have an in-depth understanding of some important concepts to write code better and implement business functions. Below we will introduce several important and commonly used knowledge points. Mastering these concepts can avoid confusion in future coding.
System call
“
❝
There are some built-in functions in the kernel of all operating systems, which can be used to complete some system-level functions. In Linux systems, these functions are called "system calls". They represent a transition from user space to kernel space.
❞
”
Message received. For beginners, if they want to program in a Linux environment, they must have an in-depth understanding of some important concepts to write code better and implement business functions. Below we will introduce several important and commonly used knowledge points. Mastering these concepts can avoid confusion in future coding. ## System call > ❝ > > There are some built-in functions in the kernel of all operating systems, which can be used to complete some system-level functions. In Linux systems, these functions are called "system calls" (system call) .They represent a conversion from user space to kernel space. > > ❞
4Total 5
Like or dislike more
- System calls are services provided by the Linux operating system and are the interface for writing communications between applications and the kernel, which is what we call functions. Compared with ordinary function calls, the performance consumption of system calls is relatively large. Therefore, while the program pursues performance, try to avoid system calls.
- User-mode programs pass parameters through the stack by default. For system calls, kernel mode and user mode use different stacks, which makes system call parameters only pass through registers.
IO operation
“
❝
What is IO, in layman’s terms it means input and output
❞
”
- IO is divided into standard IO and file IO. Our commonly used scanf, printf, getchar, putchar, gets, puts are all standard input and output. Under the Linux system, everything is a file, so there are two types of file IO operations: standard IO and file IO in programming under Linux. Standard IO is buffered IO and belongs to library functions, while file IO is unbuffered and belongs to system calls.
Standard IO:
1.标准IO是由ANSIC标准定义 2.跨平台,可以在windows下运行,也可以在Linux下运行 3.通过缓冲机制来减少系统调用,实现更高的效率 4.文件流 标准IO用结构体类型来存放文件的相关信息,标准IO所有操作围绕着FILE来操作。
File IO:
1.文件IO是POSIX提供的一组函数 2.只能运行在可移植操作系统中,不能跨平台 3.没有缓冲机制 4.文件描述符是一个非负整数,每打开一个文件,系统会自动分配一个文件描述符(即从系统最小的且没有被用的描述符来分配)
原子操作
“
❝
原子在化学课程中是不可再分的颗粒。而对于Linux系统来说所谓原子操作是为了确保对一个整型数据的更改具有排他性。原子操作就是要么不执行,一旦执行就会执行完成,是不可被打断的一个,或一系列的动作,即在完成任务前不会被其他事件所打断,就像原子不可被分割成颗粒一样。单处理中,可以用单条指令完成的指令可以被看成是一个原子操作。软件中的原子操作依赖于硬件原子操作的支持。当然原子操作,也可以当引用计数使用。
❞
”
- 原子操作其实本质上和锁实现同样的功能,都是为了保护共享对象,它具有原子性,和顺序性。原子性确保指令执行期间不被打断,要么全部执行,要么根本不执行。而顺序性确保即使两条或多条指令出现在独立的执行线程中,甚至独立的处理器上,它们本该执行的顺序依然要保持。
线程安全
“
❝
所谓线程安全,就是指代码可以在多线程环境下安全地执行,输出我们想要的结果。即符合正确的逻辑,是程序员期望的正常执行结果。为了实现线程安全,Linux系统提供一些列的方法,或者只能使用局部变量或资源,或者就是利用锁等同步机制,来实现全局变量或资源的访问。
❞
”
- 线程安全在Linux环境编程中极其重要,我们不仅要了解概念,更重要的是要在实际的编程中学会实现线程安全方式。下面来看一个简单的例子:
#include #include #include static int nCnt = 0; void * Thread(void * arg) { for (int i = 0; i return NULL; } int main() { pthread_t t1; pthread_t t2; /* 创建两个线程 */ pthread_create(&t1, NULL, thread, NULL); pthread_create(&t2, NULL, thread, NULL); pthread_join(t1, NULL); pthread_join(t2, NULL); printf("nCnt is %d by threads\n", nCnt); return 0; }
- 大家看出上面例子的问题了吗?
-
对,没错,在此例子中我们创建了两个线程,线程函数是同一个函数,在线程函数中是对全局变量
nCnt
的自增操作。这个例子中输出结果和我们想要的是不一样,就是因为nCnt
执行指令并不是原子的,两个个线程对nCnt
的并发访问出现了问题。我们利用锁就可以解决此问题。
阻塞与非阻塞
“
❝
Linux环境编程中的阻塞与非阻塞,都是指I/O操作。而所有的I/O系统调用默认都是阻塞的。那什么是阻塞? 阻塞的系统调用是指当进行系统调用时除非出错或被信号打断,那么系统调用将会一直陷入内核态直到调用完成。非阻塞的系统调用是指无论I/O操作成功与否,调用都会立刻返回。阻塞和非阻塞IO是访问设备的两种模式,驱动程序可以灵活的支持这两种用户空间对设备的访问方式。
❞
”
- 阻塞操作是指在执行操作时,若不能获得资源,则阻塞进程直到满足条件再进行操作。被阻塞的进程进入睡眠状态,被调度器的运行队列移走,直到等待的条件满足
- 非阻塞是指在进行操作时,若不能获得资源,他要么放弃,要么返回后重新查询,直到可以进行操作为止。
-
当数据准备好时二者的模式相同,即
IO操作
都是将进程阻塞,直到IO操作
完成 - 阻塞、非阻塞是设备文件、网络文件的属性
同步与异步
“
❝
同步与异步,也是指I/O操作。POSIX定义如下:A synchronous I/O operation causes the requesting process to beblocked until that I/O operation completes An asynchronous I/O operation does not cause the requesting processto be blocked
❞
”
-
The difference between the two is that synchronous IO will block the process when doing
IO operations
, while asynchronous IO will not block the process when doingIO operations
- When blocking, non-blocking, synchronous and asynchronous are put together, confusion inevitably arises. Does synchronization mean blocking, and does asynchronous means non-blocking? In fact, in I/O operations, they are different concepts. Synchronization can be either blocking or non-blocking, and commonly used Linux I/O calls are actually synchronous. The synchronization and asynchronousness here refer to whether the copying of I/O data is executed synchronously.
- Take the system call read as an example. The blocking read will remain in the kernel state until read returns; the non-blocking read will return directly when the data is not ready, and when there is data, the non-blocking read will also remain in the kernel state until the read is completed. This read is a synchronous operation, that is, the completion of I/O is completed synchronously under the current execution process. If it is asynchronous, the I/O operation is not completed synchronously with the system call. After the call returns, the I/O operation is not completed. Instead, the operating system or a certain thread is responsible for the real I/O operation, and the original thread is notified after completion
The above is the detailed content of Several concepts that must be understood in Linux environment programming. For more information, please follow other related articles on the PHP Chinese website!


For years, Linux software distribution relied on native formats like DEB and RPM, deeply ingrained in each distribution's ecosystem. However, Flatpak and Snap have emerged, promising a universal approach to application packaging. This article exami

The differences between Linux and Windows in handling device drivers are mainly reflected in the flexibility of driver management and the development environment. 1. Linux adopts a modular design, and the driver can be loaded and uninstalled dynamically. Developers need to have an in-depth understanding of the kernel mechanism. 2. Windows relies on the Microsoft ecosystem, and the driver needs to be developed through WDK and signed and certified. The development is relatively complex but ensures the stability and security of the system.

The security models of Linux and Windows each have their own advantages. Linux provides flexibility and customizability, enabling security through user permissions, file system permissions, and SELinux/AppArmor. Windows focuses on user-friendliness and relies on WindowsDefender, UAC, firewall and BitLocker to ensure security.

Linux and Windows differ in hardware compatibility: Windows has extensive driver support, and Linux depends on the community and vendors. To solve Linux compatibility problems, you can manually compile drivers, such as cloning RTL8188EU driver repository, compiling and installing; Windows users need to manage drivers to optimize performance.

The main differences between Linux and Windows in virtualization support are: 1) Linux provides KVM and Xen, with outstanding performance and flexibility, suitable for high customization environments; 2) Windows supports virtualization through Hyper-V, with a friendly interface, and is closely integrated with the Microsoft ecosystem, suitable for enterprises that rely on Microsoft software.

The main tasks of Linux system administrators include system monitoring and performance tuning, user management, software package management, security management and backup, troubleshooting and resolution, performance optimization and best practices. 1. Use top, htop and other tools to monitor system performance and tune it. 2. Manage user accounts and permissions through useradd commands and other commands. 3. Use apt and yum to manage software packages to ensure system updates and security. 4. Configure a firewall, monitor logs, and perform data backup to ensure system security. 5. Troubleshoot and resolve through log analysis and tool use. 6. Optimize kernel parameters and application configuration, and follow best practices to improve system performance and stability.

Learning Linux is not difficult. 1.Linux is an open source operating system based on Unix and is widely used in servers, embedded systems and personal computers. 2. Understanding file system and permission management is the key. The file system is hierarchical, and permissions include reading, writing and execution. 3. Package management systems such as apt and dnf make software management convenient. 4. Process management is implemented through ps and top commands. 5. Start learning from basic commands such as mkdir, cd, touch and nano, and then try advanced usage such as shell scripts and text processing. 6. Common errors such as permission problems can be solved through sudo and chmod. 7. Performance optimization suggestions include using htop to monitor resources, cleaning unnecessary files, and using sy


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
