Linux 文件系统
2018-01-25
物理结构
- 机械硬盘 Disk -> 盘片/盘面 Platter -> 磁道 Tracker -> 扇区 Physical Sector
- 光盘
- SSD -> NAND Package -> Die -> Plane -> Block -> Page
- 非易失性存储器(永久):NAND Flash
- 易失性存储器(临时):DRAM
扇区大小是厂商定的,一般是 512B 的倍数。
老的机械硬盘一般是 512B 扇区,新的机械硬盘一般是 4K 扇区(AF,Advanced Format)
光盘(CD/DVD)一般是 2K 扇区。
处于向前兼容的目的,其他类型存储设备的大小也一般是 512B。
逻辑结构
- 逻辑扇区 Logical Sector
- 块 Block
Windows 下叫做 簇 Cluster,或者磁盘分配单元。
PS:内存上的类似概念,是段 Segment 和页 Page
$ sudo fdisk /dev/sda -l
Disk /dev/sda: 40 GiB, 42949672960 bytes, 83886080 sectors
Disk model: VBOX HARDDISK
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: 7EC7FA37-FE79-46C1-A404-56AA0E00CFAB
Device Start End Sectors Size Type
/dev/sda1 2048 4095 2048 1M BIOS boot
/dev/sda2 4096 4198399 4194304 2G Linux filesystem
/dev/sda3 4198400 83884031 79685632 38G Linux filesystem
格式化
https://zh.wikipedia.org/wiki/磁盘格式化
对于部分硬盘制造厂商,它也被称为初始化。
最早,低级格式化被用于指代对磁盘进行划分柱面、磁道、扇区的操作。
现今,随着软盘的逐渐退出日常应用,应用新的编址方法和接口的磁盘的出现,这个词已经失去了原本的含义,大多数的硬盘制造商将低级格式化定义为创建硬盘扇区(sector)使硬盘具备存储能力的操作。现在,人们对低级格式化存在一定的误解,多数情况下,提及低级格式化,往往是指硬盘的填零操作。
- 高级格式化、逻辑格式化
根据用户选定的文件系统,在磁盘的特定区域写入特定数据,以达到初始化磁盘或磁盘分区、清除原磁盘或磁盘分区中所有文件的一个操作。
高级格式化包括对主引导记录中分区表相应区域的重写、根据用户选定的文件系统,在分区中划出一片用于存放文件分配表、目录表等用于文件管理的磁盘空间,以便用户使用该分区管理文件。
常见文件系统类型
- FAT / FAT32 / exFAT
- NTFS
- EXT2 / EXT3 / EXT4
- BTRFS
- Apple HFS
参考资料与拓展阅读
Python 网络编程
2018-01-23
import socket
import signal
import sys
import os
def handle_connection(conn):
conn.close()
def worker(sock):
while True:
try:
conn, addr = sock.accept()
handle_connection(conn)
except OSError as e:
if e.errno == socket.ECONNABORTED:
# 忽略 ECONNABORTED 错误
pass
else:
raise
def main():
port = 8080
backlog = 10 # 连接队列长度(超出会拒绝或忽略)
num_workers = 4 # 子进程数
# 创建监听器
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(('localhost', port))
listener.listen(backlog)
sock.setblocking(False)
print(f"Listening on port {port}...")
# # “来一个连接,起一个进程”的模式
# def sig_handler(sig, frame):
# listener.close()
# sys.exit(0)
# signal.signal(signal.SIGINT, sig_handler)
# signal.signal(signal.SIGTERM, sig_handler)
# while True:
# conn, addr = listener.accept()
# pid = os.fork()
# if pid == 0:
# listener.close()
# handle_connection(conn)
# sys.exit(0)
# else:
# conn.close()
# 子进程放到进程组中
os.setpgrp()
# 多个 worker 子进程一同监听端口的模式
processes = []
for i in range(num_workers):
p = Process(target=worker, args=(sock,))
processes.append(p)
p.start()
# 通过 os.killpg 向进程组发送信号
signal.signal(signal.SIGINT, lambda signum, frame: os.killpg(0, signal.SIGINT))
signal.signal(signal.SIGTERM, lambda signum, frame: os.killpg(0, signal.SIGTERM))
signal.pause()
for p in processes:
p.terminate()
if __name__ == '__main__':
main()
惊群效应是指事件发生的时候,多个进程或线程竞争处理这个事件,导致系统负载出现一个尖峰。严重的情况下可能导致系统瘫痪。
虽然 accept 会阻塞住,只有一个抢到,但是惊群的问题应该还是存在。
进程组
os.setpgrp 设置进程组
os.killpg 向进程组发送信号,如果没有设置进程组,这个操作没有意义
os.set_inheritable 继承文件描述符,然后可以独立使用和关闭
Python
2018-01-22
内存分配
- 堆内存 heap
- 垃圾回收:
- 引用计数
- 延迟回收(支持手动触发)
引用计数
标记所有当前正在使用的对象,然后清除所有未被标记的对象来回收内存。
这个算法的缺点是当内存中有大量未被标记的垃圾时,清除过程可能会变得非常缓慢。
将对象分为三代:
- 新创建的对象放在第 0 代
- 第 1 代包含一些活跃的对象
- 第 2 代包含一些非常稳定的对象
不同代执行不同的标记策略。
相关工具
Python 中有一些内置的工具可以用于检查内存使用、内存分配情况以及各类对象数量的统计,下面列举一些常用的方法:
- memory_profiler 模块可以检查内存使用情况
@profile 装饰器 + -m memory_profiler 参数,输出每个代码行的内存占用情况,以及整个程序的内存使用情况。
- objgraph 模块可以检查内存中各类对象的数量
objgraph.show_refs() 对象引用图
objgraph.show_most_common_types() 对象数量统计
- gc 模块可以手动管理内存
gc.collect() 手动触发垃圾回收
gc.get_count() 垃圾回收相关信息
- pympler
- meliae
手动释放内存:
Windows 命令行
2018-01-15
Active Directory
ADmodcmd Active Directory Bulk Modify
CSVDE Import or Export Active Directory data
DSACLs Active Directory ACLs
DSAdd Add items to active directory (user group computer)
DSGet View items in active directory (user group computer)
DSQuery Search for items in active directory (user group computer)
DSMod Modify items in active directory (user group computer)
DSMove Move an Active directory Object
DSRM Remove items from Active Directory
Batch Files
CALL Call one batch program from another 内部命令
CHOICE Accept keyboard input to a batch file
CLIP Copy STDIN to the Windows clipboard
CLS Clear the screen 内部命令
CMD Start a new CMD shell
COLOR Change colors of the CMD window 内部命令
DOSKEY Edit command line, recall commands, and create macros
ECHO Display message on screen 内部命令
ENDLOCAL End localisation of environment changes in a batch file 内部命令
EVENTCREATE Add a message to the Windows event log
EXIT Quit the current script/routine and set an errorlevel 内部命令
FOR /F Loop command: against a set of files 内部命令
FOR /F Loop command: against the results of another command 内部命令
FOR Loop command: all options Files, Directory, List 内部命令
GOTO Direct a batch program to jump to a labelled line 内部命令
IF Conditionally perform a command 内部命令
IFMEMBER Is the current user a member of a Workgroup
LOGTIME Log the date and time in a file
MAPISEND Send email from the command line
MORE Display output, one screen at a time
PAUSE Suspend processing of a batch file and display a message 内部命令
PROMPT Change the command prompt 内部命令
REM Record comments (remarks) in a batch file 内部命令
RUN Start | RUN commands
RUNAS Execute a program under a different user account
SET Display, set, or remove session environment variables 内部命令
SETLOCAL Control the visibility of environment variables 内部命令
SETX Set environment variables
SORT Sort input
SHIFT Shift the position of batch file parameters 内部命令
SLEEP Wait for x seconds
START Start a program, command or batch file 内部命令
TIMEOUT Delay processing of a batch file
TITLE Set the window title for a CMD.EXE session 内部命令
WAITFOR Wait for or send a signal
WMIC WMI Commands
:: Comment / Remark 内部命令
Disk Management
BCDBOOT Create or repair a system partition
BCDEDIT Manage Boot Configuration Data
CONVERT Convert a FAT drive to NTFS
CHKDSK Check Disk - check and repair disk problems
CHKNTFS Check the NTFS file system
DEFRAG Defragment hard drive
DISKPART Disk Administration
DISKSHADOW Volume Shadow Copy Service
DriverQuery Display installed device drivers
FORMAT Format a disk
FREEDISK Check free disk space (in bytes)
LABEL Edit a disk label
MOUNTVOL Manage a volume mount point
NTBACKUP Backup folders to tape
SFC System File Checker
VOL Display a disk label 内部命令
Files and Folders
ASSOC Change file extension associations 内部命令
ASSOCIAT One step file association
ATTRIB Change file attributes
BITSADMIN Background Intelligent Transfer Service
CACLS Change file permissions
CD Change Directory - move to a specific Folder 内部命令
CIPHER Encrypt or Decrypt files/folders
COMP Compare the contents of two files or sets of files
COMPACT Compress files or folders on an NTFS partition
COMPRESS Compress individual files on an NTFS partition
COPY Copy one or more files to another location 内部命令
CSCcmd Client-side caching (Offline Files)
DEL Delete one or more files 内部命令
DELTREE Delete a folder and all subfolders
DIR Display a list of files and folders 内部命令
ERASE Delete one or more files 内部命令
EXPAND Uncompress files
EXTRACT Uncompress CAB files
FC Compare two files
FIND Search for a text string in a file
FINDSTR Search for strings in files
FORFILES Batch process multiple files
FSUTIL File and Volume utilities
FTP File Transfer Protocol
FTYPE File extension file type associations 内部命令
iCACLS Change file and folder permissions
MD Create new folders 内部命令
MOVE Move files from one folder to another 内部命令
MKLINK Create a symbolic link (linkd)
OPENFILES Query or display open files
POPD Return to a previous directory saved by PUSHD 内部命令
PsFile Show files opened remotely
PUSHD Save and then change the current directory 内部命令
RECOVER Recover a damaged file from a defective disk
REN Rename a file or files 内部命令
REPLACE Replace or update one file with another
RD Delete folder(s) 内部命令
RMTSHARE Share a folder or a printer
ROBOCOPY Robust File and Folder Copy
SHARE List or edit a file share or print share
SHORTCUT Create a windows shortcut (.LNK file)
SUBINACL Edit file and folder Permissions, Ownership and Domain
TAKEOWN Take ownership of a file
TOUCH Change file timestamps
TREE Graphical display of folder structure
TYPE Display the contents of a text file 内部命令
WHERE Locate and display files in a directory tree
WINDIFF Compare the contents of two files or sets of files
XCACLS Change file and folder permissions
XCOPY Copy files and folders
Group Policy/Windows Installer
DevCon Device Manager Command Line Utility
GPRESULT Display Resultant Set of Policy information
GPUPDATE Update Group Policy settings
MSIEXEC Microsoft Windows Installer
PsInfo List information about a system
PsShutdown Shutdown or reboot a computer
REGSVR32 Register or unregister a DLL
SHUTDOWN Shutdown the computer
SLMGR Software Licensing Management (Vista/2008)
WUAUCLT Windows Update
Networking
ARP Address Resolution Protocol
BROWSTAT Get domain, browser and PDC info
DNSSTAT DNS Statistics
GETMAC Display the Media Access Control (MAC) address
IPCONFIG Configure IP
NET Manage network resources
NETDOM Domain Manager
NETSH Configure Network Interfaces, Windows Firewall & Remote access
NBTSTAT Display networking statistics (NetBIOS over TCP/IP)
NETSTAT Display networking statistics (TCP/IP)
NMBIND Manage Hyper-V network bindings
NSLOOKUP Name server lookup
PATHPING Trace route plus network latency and packet loss
PsPing Measure network performance
PING Test a network connection
ROUTE Manipulate network routing tables
TRACERT Trace route to a remote host
Processes
PATH Display or set a search path for executable files 内部命令
PsExec Execute process remotely
PsKill Kill processes by name or process ID
PsList List detailed information about processes
PsGetSid Display the SID of a computer or a user
PsSuspend Suspend processes
SCHTASKS Schedule a command to run at a specific time
SYSMON Monitor and log system activity to the Windows event log
TASKLIST List running applications and services
TASKKILL End a running process
TSKILL End a running process
TLIST Task list with full path
Printing
MODE Configure a system device
PRINT Print a text file
PRINTBRM Print queue Backup/Recovery
RUNDLL32 Run a DLL command (add/remove print connections)
Recovery
BOOTREC Repair or replace a partition boot sector (WinRE).
BCDBOOT Create or repair a system partition.
BCDEDIT Manage Boot Configuration Data.
WPEUTIL Run commands during a Windows Preinstallation Environment (WinPE) session.
Registry
REG Registry: Read, Set, Export, Delete keys and values
REGEDIT Import or export registry settings
REGINI Change Registry Permissions
Remote Desktop
CHANGE Change Terminal Server Session properties
Query Process Display processes (TS/Remote Desktop)
Query Session Display all sessions (TS/Remote Desktop)
Query TermServer List all servers (TS/Remote Desktop)
Query User Display user sessions (TS/Remote Desktop)
MSTSC Terminal Server Connection (Remote Desktop Protocol)
RASDIAL Manage RAS connections
RASPHONE Manage RAS connections
Reset Session Delete a Remote Desktop Session
TSDISCON Disconnect a Remote Desktop Session
WINRM Windows Remote Management
WINRS Windows Remote Shell
Services
CASPOL Code Access Security Policy Tool.
PORTQRY Display the status of ports and services
PsService View and control services
SC Service Control
System Information
CHANGEPK Upgrade device Edition/Product Key
DATE Display or set the date 内部命令
HELP Online Help
LOGMAN Manage Performance Monitor logs
MBSAcli Baseline Security Analyzer
MSINFO32 System Information
NOW Display the current Date and Time
NTRIGHTS Edit user account rights
PsLogList Event log records
SFC System File Checker
SXSTRACE Diagnose side-by-side problems.
SYSMON Monitor and log system activity to the Windows event log
SYSTEMINFO List system configuration
TIME Display or set the system time 内部命令
TypePerf Write performance data to a log file
VER Display version information 内部命令
VERIFY Verify that files have been saved 内部命令
WHOAMI Output the current UserName and domain
User Administration
ADDUSERS Add or list users to/from a CSV file
CERTREQ Request certificate from a certification authority
CleanMgr Automated cleanup of Temp files, recycle bin
CON2PRT Connect or disconnect a Printer
CMDKEY Manage stored usernames/passwords
DELPROF Delete user profiles
DIRUSE Display disk usage
LOGOFF Log a user off
MOVEUSER Move a user from one domain to another
MSG Send a message
PERMS Show permissions for a user
POWERCFG Configure power settings
PsLoggedOn Who's logged on (locally or via resource sharing)
PsPasswd Change account password
SUBST Associate a path with a drive letter
Commands marked • are Internal commands only available within the CMD shell.
All other commands (not marked with •) are external commands.
External commands may be used under the CMD shell, PowerShell, or directly from START-RUN.
参考资料与拓展阅读
Bash Linux 命令行
2018-01-11
我写 Shell 脚本一般都是用 bash 执行,一般我会在头部插入 set -xue 命令, 助记:蛇血。
那么这个命令的作用是什么呢?
set 是 bash 提供的一个命令,用来管理 bash 的一些行为。
x: 在执行命令前,输出所有命令,包括参数。
u: 遇到未定义变量时,报错。
e: 如果遇到错误,程序退出。
其他更多参数,参考:set --help 或 help set。
Redis
2018-01-10
测试环境
keys *
删除指定模式的 key:
redis-cli keys 'a.b.*' > /tmp/deleted_keys
cat /tmp/deleted_keys
cat /tmp/deleted_keys | xargs redis-cli del
线上环境
线上 keys 可能会导致严重的性能问题。
2.8 开始,Redis 增加了 4 个 SCAN 命令:
SCAN cursor [MATCH pattern] [COUNT count] [TYPE type] 遍历当前 db 中的所有键, 返回 keys ...
SSCAN key cursor [MATCH pattern] [COUNT count] 遍历 set 类型,返回 value ...
HSCAN key cursor [MATCH pattern] [COUNT count] 遍历 hash 类型,返回 (key, value)
ZSCAN key cursor [MATCH pattern] [COUNT count] 遍历 sorted set 类型,返回 (score, member)
scan 0 count 100
每次会返回一个新的游标,用于下一次 scan 请求。
import redis
r = redis.StrictRedis(host='localhost', port=6379, db=0)
for key in r.scan_iter():
print(key)
WebDev ECharts
2018-01-04
一般都是参考着 官网示例 写,修修改改就好了,挺方便。
Linux Vim 编辑器 CheatSheet
2018-01-03
我并不是个 Vim 高手,但是我所掌握的知识对于轻量使用来说,也够用了。
这就是我能想到的全部 Vim 知识。
如果你是一个新手,看看这篇文章,应该可以快速入门 Vim,能解决所有简单编辑任务所会面临的问题。
基础知识
避免由于意外操作而不知所措。
模式
- 普通模式(Normal):直接打开文件(
vim filepath)就进入了这个模式,可以移动光标,执行一些指令
- 插入模式(Insert):像普通编辑器一样编辑文本
- 可视模式(Visual):先在普通模式下移动光标到目标区域,然后切换到可视模式,这时移动光标就可以选中一块区域,对着块区域的内容执行一些命令
- 命令模式:在 Vim 底部输入命令,按回车执行
- 选择模式(Select):正常我们能够理解的选中,然后删除或者对着一块进行替换
- Ex 模式:。。。
模式切换:
- 在任何模式下按 Esc 就可以回到普通模式;
- 普通模式下,按
i 进入插入模式;
- 普通模式下,按
v 进入可视模式(字符);
- 普通模式下,按
V 进入行可视模式;
- 普通模式下,按
Ctrl + v 进入块可视模式;
- Windows 系统下 Ctrl + v 被占用作为粘贴快捷键,可以使用 Ctrl + q 代替;
- 普通模式下,按
: 进入命令模式;
- 可视模式下,按
Ctrl + g 进入选择模式;
- 选择模式下,可以按
Ctrl + o 回退到可视模式;
快捷键
上下左右,翻页(PageUp,PageDown),删除(Backspace,Del)本身就可以用,就不用记快捷键了。
| Key |
Function |
u |
撤销 |
dd |
删除当前行 |
3dd |
删除当前行 + 后面两行(共 3 行) |
>> |
缩进 |
<< |
取消缩进 |
== |
自动对齐 |
使用命令 5d 删除第五行
使用命令 5,10d 删除第 5 到第 10 行
跳转
| Key |
Function |
gg |
跳到第一行 |
20gg |
跳到第 20 行 |
G |
跳到最后一行 |
10j |
往前跳 10 行 |
10k |
往后跳 10 行 |
hjkl 本身用来表示左上下右,所以...
复制粘贴
| Key |
Function |
yy |
复制当前行 |
3yy |
复制当前行 + 后面两行(共 3 行) |
yw |
复制当前单词和后面的空白字符 |
p |
Paste 粘贴在当前行、字符后面 |
P |
Paste 粘贴在当前行、字符前面 |
搜索
| Key |
Function |
? |
向后搜索(正则) |
/ |
向前搜索(正则) |
# |
向后搜索当前单词,等同于输入 #\<xxx\> |
* |
向前搜索当前单词,等同于输入 /\<xxx\> |
- n/N 跳到上一处或下一处
\cp[a-z]*n 忽略大小写,搜索 p 开头,n 结尾的单词
命令
一般都有取消配置的 set noXXX 命令。
| Key |
Function |
set nu |
显示行号 |
set paste |
粘贴模式(避免开启自动缩进时,会弄乱粘贴内容) |
set ignorecase / set ic |
搜索忽略大小写 |
set hlsearch |
高亮搜索结果(似乎是默认) |
set nohlsearch |
取消高亮搜索结果 |
noh |
关闭高亮 |
set listchars=tab:>~,trail:. |
显示 TAB 键和行末空格 |
set cursorline |
当前行加上下划线 |
替换
| Key |
Function |
s/Gitee/Gitea/g |
将当前行所有 Gitee 替换成 Gitea |
%s/Gitee/Gitea/g |
将所有行所有 Gitee 替换成 Gitea |
%s/Gitee/Gitea/gi |
...忽略大小写 |
%s/Gitee/Gitea/gin |
...不真正执行,只反馈印象范围 |
5,10s/Gitee/Gitea/g |
将第 5 到 10 行所有 Gitee 替换成 Gitea |
.,+5s/Gitee/Gitea/g |
将当前行到后两行所有 Gitee 替换成 Gitea |
保存
| Key |
Function |
q |
退出(可能会提示你:已修改但尚未保存) |
w |
保存 |
wq |
保存并退出 |
x |
保存并退出 |
q! |
不保存,强行退出 |
:w !sudo tee % |
没有写入权限的时候提权保存 |
清空数据:gg + 1000dd(跳到第一行,然后删除 1000 行)
> filepath
# 或
echo > filepath
参考资料与拓展阅读
包管理工具 Linux Ubuntu Debian APT
2017-12-25
搜索
apt search xxx
检索
apt list
apt list --installed
apt list --upgradable
升级
apt update
apt upgrade
apt-file
apt-file list youtube-dl
apt-file search bin/update-locale
其他
apt search
apt show
apt install
apt reinstall
apt remove
apt autoremove
apt full-upgrade
apt edit-sources
apt satisfy
apt-mark
apt-key
apt-config
apt-cache
apt-add-repository
Git
2017-12-07
CR:Carriage Return 回车
LF:Line Feed 换行
EOL: End Of Line
| 平台 |
代码 |
数值 |
转义字符 |
| Windows |
CRLF |
13 10 |
\r\n |
| Linux/Unix |
LF |
10 |
\n |
| Mac OS |
CR |
13 |
\r |
Git 相关配置项
core.eol,换行符,可选:lf,crlf,native(根据系统判断,默认)
core.safecrlf,是否接受非 LF 换行,可选:true(拒绝),false(允许),warn(警告,默认)
core.autocrlf,是否自动转换换行符,可选:true(push lf,pull crlf),false(默认),input(push lf)
Linux 上,这三个配置项的默认值就非常恰当了,不用修改。
代码中的换行符应该由开发者自己判断、处理,工具提醒一下就行了。
如果项目组有共识,那么使用一个共同的配置也可以,比如:
git config --global core.eol lf
git config --global core.safecrlf true
git config --global core.autocrlf input
# 如果 CRLF 转换,会有警告提示:
# warning: in the working copy of 'README.md', CRLF will be replaced by LF the next time Git touches it