当前位置:网站首页>Interview question: is the space released after RM deleted the file? Do you know the answer?

Interview question: is the space released after RM deleted the file? Do you know the answer?

2020-12-06 16:01:47 Irving the procedural ape

  • Generate a random content file of a specified size

  • When will a file be deleted ?

  • How to free the space occupied by deleted files ?

  • summary

stay Linux, Did you ever think that , Use rm Delete a file , The space is free ? Things may not always be what you want .

Generate a random content file of a specified size

Let's take a look at the current space size of each mounted directory :

$ df -h/dev/sda11  454M 280M 147M 66% /boot

 

I picked one of the results here ( You can choose any mount Directory ), Next, we are going to /boot Next generate a file .

First we have a 50M Size file :

$ dd if=/dev/urandom of=/boot/test.txt bs=50M count=1

 

thus , We produced a 50M Size file , Look again boot Next :

$ df -h/dev/sda11  454M 312M 115M 74% /boot

 

You don't have to worry about how much more , You just need to pay attention ,/boot There are more files under .

The test program :

#include<stdio.h>#include<unistd.h>int main(void){ FILE *fp = NULL; fp = fopen("/boot/test.txt", "rw+"); if(NULL == fp) {  perror("open file failed");  return -1; } while(1) {  //do nothing  sleep(1); } fclose(fp); return 0;}

 

As for the program itself , I didn't do anything practical , Just open a file , And then it goes on and on . Compile and run :

$ gcc -o openFile openFile.c$ ./openFile

 

Open another window , Delete test.txt:

$ rm /boot/test.txt

 

Look again. boot Space :

$ df -hdev/sda11  454M 312M 115M 74% /boot

 

Why ? The size of the space hasn't changed at all !! Clearly use rm Delete it ?

We put openFile The program stops , I want to see others :

$$ df -h/dev/sda11  454M 280M 147M 66% /boot

 

Darling , The space was immediately released , That is, as expected , Our files have been deleted .

When will a file be deleted ?

actually , Only when the reference count of a file is 0( Including the number of hard links ) When , It's possible to call unlink Delete , As long as it's not 0, Then it won't be deleted . The so-called deletion , It's just a file name inode Link to delete , As long as the data is not rewritten , On disk block Data blocks are not deleted ,.........

版权声明
本文为[Irving the procedural ape]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/20201206160044900m.html