慢慢欣赏linux 截断文件

本文深入探讨了在Linux系统中使用echo与truncate命令截断文件的两种方式,详细解析了其内核态行为及调用流程,为理解Linux文件操作提供了一线视角。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

echo > /root/test.txt和truncate -s 0 /test.txt都可以截断文件。
如果文件句柄没有被关闭,仍然被别的进程占据写的话可以将文件的前半部分变成空洞。

前者在内核态行为是通过sys_open调用下来的

ret_from_syscall
	=>asmlinkage long sys_open(const char __user *filename, int flags, int mode);
		struct file *f = do_filp_open(dfd, tmp, flags, mode, 0);
			=>struct file *do_filp_open(int dfd, const char *pathname, int open_flag, int mode, int acc_mode)
				filp = do_last(&nd, &path, open_flag, acc_mode, mode, pathname);
					=>static struct file *do_last(struct nameidata *nd, struct path *path, int open_flag, int acc_mode, int mode, const char *pathname)
						filp = finish_open(nd, open_flag, acc_mode);
							=>static struct file *finish_open(struct nameidata *nd, int open_flag, int acc_mode)
								will_truncate = open_will_truncate(open_flag, nd->path.dentry->d_inode);
								if (will_truncate)
									error = handle_truncate(&nd->path);
										=>static int handle_truncate(struct path *path)
											do_truncate(path->dentry, 0, ATTR_MTIME|ATTR_CTIME|ATTR_OPEN, NULL);

后者是如下调用                                            

ret_from_syscall
	=>static long do_sys_ftruncate(unsigned int fd, loff_t length, int small)
		do_truncate(dentry, length, ATTR_MTIME|ATTR_CTIME, file);
			=>int do_truncate(struct dentry *dentry, loff_t length, unsigned int time_attrs, struct file *filp)
				struct iattr newattrs;
				newattrs.ia_size = length;
				ret = notify_change(dentry, &newattrs);
					=>int notify_change(struct dentry * dentry, struct iattr * attr)
						error = inode_setattr(inode, attr);
							=>int inode_setattr(struct inode * inode, struct iattr * attr)
								int error = vmtruncate(inode, attr->ia_size);
									=>int vmtruncate(struct inode *inode, loff_t offset)
										error = inode_newsize_ok(inode, offset);
										oldsize = inode->i_size;
										i_size_write(inode, offset);
											=>static inline void i_size_write(struct inode *inode, loff_t i_size)
												inode->i_size = i_size;
										truncate_pagecache(inode, oldsize, offset);
										inode->i_op->truncate(inode);
								mark_inode_dirty(inode);


        
linux系统编程:用truncate调整文件大小
https://www.cnblogs.com/ghostwu/archive/2018/01/11/8269220.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值