Table of Contents
What is Direct IO
Create and write files
Reading files
File operation
Other settings
总结
Home Backend Development PHP Problem How to use DirectIO in PHP

How to use DirectIO in PHP

Jul 12, 2021 pm 02:57 PM
php

Regarding PHP file operations, we will also learn through a series of articles. Today we will first learn about an extension that few people have used, and many people even don’t know about it. It is slightly different from our daily file operations. However, these differences are not intuitively visible to our naked eyes. They mainly lie in the balance between business needs and performance.

How to use DirectIO in PHP

What is Direct IO

Direct IO is actually a concept in the Linux operating system. It means to directly operate the file stream. Why is it said to be direct? In fact, when our operating system performs file operations, it does not directly read and write files on the disk immediately. There is a layer of page cache in the middle.

Since it is a cache, it will certainly bring a certain performance improvement, but this is not completely absolute. The direct operation is to ignore this layer of cache operations and directly read and write files on the disk. We all know that there is a huge gap between the processing speed of disks, even solid-state drives, and CPU and memory. The default page cache is used to bridge this gap.

However, the page cache will increase the computing operations of the CPU and occupy memory. Direct operation does not have this problem, but relatively speaking, its speed is not comparable to the file reading operation with cache. Comparable.

The above is a simple understanding of Direct IO. For a more detailed explanation, you can refer to the second link in the reference document at the end of the article and conduct in-depth study. In PHP, we download the Direct IO extension directly from PECL and install it according to the normal installation method of the extension.

Create and write files

Since it is a file operation, let us first create and write some file data.

$fd = dio_open("./test", O_RDWR | O_CREAT);

echo dio_write($fd, "This is Test.I'm ZyBlog.Show me the money4i"), PHP_EOL;
// 43

print_r(dio_stat($fd));
// Array
// (
//     [device] => 64768
//     [inode] => 652548
//     [mode] => 35432
//     [nlink] => 1
//     [uid] => 0
//     [gid] => 0
//     [device_type] => 0
//     [size] => 43
//     [block_size] => 4096
//     [blocks] => 8
//     [atime] => 1602643459
//     [mtime] => 1602656963
//     [ctime] => 1602656963
// )

dio_close($fd);
Copy after login

Similar to the f series functions, we need to use a dio_open() function to open a file. The O_RDWR | O_CREAT parameter means to open a read-write file and create it if the file does not exist. . These two constants correspond to the constants related to direct operation of files in Linux. You can also see the explanation of these constants in the link at the end of the article.

The writing operation can also be completed using a dio_write(). The content it returns is the length of the written content. Here we wrote 43 characters.

dio_stat() returns some information about the current file handle. We can see some information such as device number device, uid, gid, atime, mtime, etc. They are similar to the information we can see in Linux. In fact, it is some simple information about this file.

Reading files

Reading files can be done very simply using a function.

$fd = dio_open("./test", O_RDWR | O_CREAT);

echo dio_read($fd), PHP_EOL;
// This is Test.I'm ZyBlog.Show me the money4i

dio_close($fd);
Copy after login

dio_read() function also contains another parameter, which can read the content according to the specified byte length. We will see related examples later.

File operation

During the file reading process, we may only need to read part of the content, or start reading the file content from a certain position. The following operation function is for These two aspects operate.

$fd = dio_open("./test", O_RDWR | O_CREAT);

var_dump(dio_truncate ($fd , 20)); 
// bool(true)
echo dio_read($fd), PHP_EOL;
// This is Test.I'm ZyB

dio_seek($fd, 3); 

echo dio_read($fd), PHP_EOL;
// s is Test.I'm ZyB

dio_close($fd);
Copy after login

In fact, it can be seen from the name that dio_truncate() is used to truncate the content of the file. Here we truncate from the 20th character, and then use dio_read() to read only the first 20 characters.

dio_seek() specifies which character to start reading the content from. After we specify the starting character position as 3, the first three characters will not be read. It should be noted that dio_truncate() will modify the contents of the original file, while dio_seek() will not.

Other settings

$fd = dio_open('./test', O_RDWR | O_NOCTTY | O_NONBLOCK);

dio_fcntl($fd, F_SETFL, O_SYNC);

dio_tcsetattr($fd, array(
  'baud' => 9600,
  'bits' => 8,
  'stop'  => 1,
  'parity' => 0
));

while (($data = dio_read($fd, 4))!=false) {
    echo $data, PHP_EOL;
}
// This
//  is
// Test
// .I'm
//  ZyB

dio_close($fd);
Copy after login

dio_fcntl() function is called the fcntl function in the c function library. The purpose is to perform some specified operations on the file descriptor. This operation is also fixed with some constants. Yes, here we use F_SETFL, which means to set the file descriptor flag to the specified value. This O_SYNC means that if this descriptor is set, the write operation of the file will wait until the data is written. It doesn't end until it's on disk. Of course, this function can also be set with many other operators. You can refer to PHP's official documentation for in-depth study.

dio_tcsetattr() is used to set the terminal attributes and baud rate of the open file. baud represents the baud rate, bits represents the bits, stop represents the stop bit, and parity represents the parity bit.

This aspect requires some knowledge in "Principles of Computer Composition" and "Operating System". I am not very clear about it, so I will not explain it in detail. It can be seen from here that the basic courses in college classes are really very important. I believe that students who have studied these professional basic courses will immediately understand the role of this function.

Finally, we used the second parameter in dio_read() to read the file content according to the byte length. You can see that the read content is segment by segment in units of 4 characters in length. output.

总结

函数的学习还是比较简单的,核心的还是要知道这个扩展在什么业务场景下更适合使用。在文章开头的介绍中我们已经说明了直接操作文件与普通文件操作的一些区别,在自缓存应用或者需要传输非常大的数据时,直接操作对于 CPU 和 内存 更加地友好。

而其它情况,我们还是使用系统默认的文件操作方式就可以了。其实在大部分情况下,我们基本看不出来它们的显著区别。所以在实际应用中,还是那句话,结合业务实际情况,选择最佳的方案。

测试代码:

https://github.com/zhangyue0503/dev-blog/blob/master/php/202010/source/4.PHP中DirectIO直操作文件扩展的使用.php
Copy after login

推荐学习:php视频教程

The above is the detailed content of How to use DirectIO in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1254
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles