Deleting an open file linux

How to delete a file present in some directory in linux programmatically

My aim is to delete a file in some directory present in linux using a java program. I have the following line that does that:

java.lang.Runtime.getRuntime().exec("/bin/rm -f " + fileToDelete.getAbsolutePath()); 

But I read that using linux commands from java program would be a costlier operation. Could anyone let me know if there is another way of doing this?

4 Answers 4

boolean isFileDeleted = fileToDelete.delete(); 

I see from docs.oracle.com/javase/7/docs/api/java/nio/file/… taht «On some operating systems it may not be possible to remove a file when it is open and in use by this Java virtual machine or other programs» in that case I may need to force delete this file even if its open. I think «rm -f» does that. How to achieve that?

I would not recommend deleting open files. What if there is remaining unwritten data? I would suggest to ensure all open files are closed first. Remember it is in this JVM so you will have control over this

From what I remember Windows will block the deletion of open files but Linux won’t. Have you tried deleting an open file like this?

@user2349990, on Linux there is no problem in deleting an open file, and File.delete will call the same operating system function as the rm command, but will be a lot less expensive. The -f option only makes rm ignore files that don’t exist; usually it would report an error.

You could use a File object, as such:

// initializes your file with your full path (or use your "fileToDelete" variable) File file = new File("myFile"); // attempts to set the file writable and returns boolean result System.out.println("Could set file writable: " + file.setWritable(true)); // attempts to delete the file and returns boolean result System.out.println("Deleted succesfullly: " + file.delete()); 

Permission / delete operations may throw an unchecked SecurityException .

if(file.exists()) boolean isSuccessful = file.delete(); 

Источник

Удаление открытого файла

Кто-нибудь может знает, возможно ли удалить файл, в который идёт поток информации, т.е. файл открыт на запись другим преложением, а мне в какой-то определённый момент времени нужно его обнулить в Unix/Linux. провобoвал echo > file echo -n > file head -c 0 > file cat /dev/null > file раземр не сбрасывается!

Читайте также:  Mandriva linux 64 bit

4 ответа 4

Если файл не залочен (обычно это не делается), то его можно легко удалить. Однако, исчезновение файла из дерева файлов не будет означать его фактическое удаление. На самом деле, файл будет существовать до тех пор, пока приложение, выполняющее в него запись, не закроет его. В то же время, файл будет уже нельзя открыть. В таком промежуточном состоянии он будте продолжать занимать место на диске. Я не уверен, что это поведение воспроизводится на всех файловых системах, но под ext3 я точно наблюдал подобное.

PS: таким образом, ответ на ваш вопрос: всё-таки это плохая идея и стоит воздержаться от этого. Тем более, что это точно будет непереносимо на другие платформы (такие как Windows).

lsof на вход принимает имя файла, а раз файл удалён, то и файла нет. Следовательно, lsof скажет, что файл не найден. Но на самом деле, тело файла всё ещё существует, хотя ссылок на него из дерева файлов уже нет.

cy6ergn0m@cgmachine ~ $ cat - > ~/delete & [1] 22129 cy6ergn0m@cgmachine ~ $ [1] + suspended (tty input) cat - > ~/delete cy6ergn0m@cgmachine ~ $ /usr/sbin/lsof ~/delete COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME cat 21808 cy6ergn0m 1w REG 8,7 0 19128453 /home/cy6ergn0m/delete cy6ergn0m@cgmachine ~ $ rm -f ~/delete cy6ergn0m@cgmachine ~ $ /usr/sbin/lsof ~/delete lsof: status error on /home/cy6ergn0m/delete: No such file or directory lsof 4.83 latest revision: ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/ latest FAQ: ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/FAQ latest man page: ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/lsof_man usage: [-?abhlnNoOPRtUvVX] [+|-c c] [+|-d s] [+D D] [+|-f[gG]] [-F [f]] [-g [s]] [-i [i]] [+|-L [l]] [+m [m]] [+|-M] [-o [o]] [-p s] [+|-r [t]] [-s [p:s]] [-S [t]] [-T [t]] [-u s] [+|-w] [-x [fl]] [--] [names] Use the ``-h'' option to get more help information. 

Источник

How to delete a file in Linux where all I have is the file descriptor

I have an int file descriptor that was opened earlier (via open ) and I need to remove that file. Do I really have to first get the file name and call remove ? (e.g. via using the technique in Getting Filename from file descriptor in C) Or is there some other (linux specific OK) way of doing it solely based on the file descriptor? I have searched and the best I could find is the above answer.

Читайте также:  Отдельный раздел для линукс

No there is not. Have you considered the possibility that there might be more than one directory entry linking to the same inode (:=file) ?

@wildplasser no I haven’t :/ and I’m taking Advanced Operating Systems at GA tech, I guess I need to take OS 101 again 🙂

5 Answers 5

You can use /proc to see which path an open fd is linked to, and realpath get the full path of the symlink.

# ls -l /proc/8701/fd total 0 lr-x------ 1 root root 64 Apr 23 22:44 0 -> /dev/null lrwx------ 1 root root 64 Apr 23 22:44 1 -> /dev/null lrwx------ 1 root root 64 Apr 23 22:44 2 -> /dev/null lrwx------ 1 root root 64 Apr 23 23:19 20 -> socket:[16204] lrwx------ 1 root root 64 Apr 23 23:19 21 -> socket:[16205] lrwx------ 1 root root 64 Apr 23 22:44 3 -> socket:[18743] l-wx------ 1 root root 64 Apr 23 22:44 4 -> /var/lib/dhcp/dhclient-7a30dd46-5058-47aa-b71e-ff77cfbe4194-wlan0.lease lrwx------ 1 root root 64 Apr 23 22:44 5 -> socket:[16872] lrwx------ 1 root root 64 Apr 23 22:44 6 -> socket:[18747] 

I don’t know of any function that can remove a file based on a file descriptor, but any such function would first have to get the path anyway, and then call unlink .

A file descriptor on Linux is an association between a process and a directory entry. The directory entry is a link between a path (file name) and an inode. There can be many file descriptors associated with a directory entry, and many directory entries associated with an inode.

When you unlink a file, you are removing a link between the directory entry and the inode. If that is the last link, the file is finally removed from disk (i.e. the inode is returned to the free list, and the blocks used by the inode are also freed).

Источник

Deleting an opened file in Infinite looped process

I have doubt in the following scenario Scenario: A process or program starts with opening a file in a write mode and entering a infinite loop say example: while(1) whose body has logic to write to the opened file. Problem: What if i delete the opened or created file soon after the process enters the infinite loop

Читайте также:  Bash консоль в linux

4 Answers 4

In Unix, users really cannot delete files, they only can drop references to files. The kernel deletes the file when there are no references (hard links and open file descriptors) left.

From what you’re saying, it sounds like in reality you don’t want an infinite loop, but rather a while loop with some flag, something to the effect of

 while (file exists) perform operation 

I don’t think that’s applicable to the question — the question was: what if I open a file, enter write mode, THEN enter an infinite loop. Thus, once the loop has been entered, I’m assuming that the file does indeed exist because it was just opened beforehand. Nowhere in the question was it stated that reopening and closing would be done in the loop, so I don’t believe that would be an issue.

Sure it exists, but it won’t have the link (filename) that was «deleted» (unlinked, really), though on Linux you’ll still be able to access it via /proc//fd/

Add a line that checks to see if the file exists during the while loop. If it doesn’t exist, kill the loop.

It appears that what happens is that your file disappears (basically).

Try this, create a file test.py and put the following in it:

import os f = open('out.txt', 'w') # Open file for writing f.write("Hi Mom!") # Write something os.remove('out.txt') # Delete the file try: while True: # Do forever f.write("Silly English Kanighit!") except: f.close() 

then $ python test.py and hit enter. Ctrl-C should stop the execution. This will open, then delete the file, then continue writing to the file that no longer exists, for the reasons that have previously been mentioned.

However, if you really have a different question such as «How can I prevent my file from being accidentally deleted while I’m writing to it?» or something else, it’s probably better to ask that question.

Источник

Оцените статью
Adblock
detector