如何在Linux上创建临时文件,这些临时文件无论如何都会自动清除? [英] How to create temporary files on linux that will automatically clean up after themselves no matter what?

查看:113
本文介绍了如何在Linux上创建临时文件,这些临时文件无论如何都会自动清除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Linux上创建一个临时文件,同时确保在程序终止后该文件将消失,即使该文件被杀死或有人在错误的时刻进行了硬重启. tmpfile()是否为我处理了所有这些事情?

I want to create a temporary file on linux while making sure that the file will disappear after my program has terminated, even if it got killed or someone performs a hard reboot in the wrong moment. Does tmpfile() handle all this for me?

推荐答案

您似乎全神贯注于这样的想法,即由于某些种族条件,文件可能会留下一些痕迹,但我不会请参阅有关为什么要担心的解释.

You seem pre-occupied with the idea that files might get left behind some how because of some race condition, I don't see an explanation of why this is a concern.

由于程序的意外排序导致对同一资源的争用而导致程序无法正常运行时,就会发生竞争状态."

我假设从您对其他答案的评论中,您所关注的特别是 dead-lock ,这是尝试修复竞争条件(共享资源的争用)的结果.目前尚不清楚您担心的是,如果担心的话,调用 tmpfile()并在该函数调用 unlink()之前让程序异常退出是您最少的担心您的应用程序确实很脆弱.

I was assuming that from your comments on other answers your concern was specifically on a dead-lock which is a result of trying to remediate a race-condition ( contention of the shared resource ). It is still not clear what your concern is, calling tmpfile() and having the program exit abnormally before that function gets to call unlink() is the least of your worries if your application is really that fragile.

鉴于没有提到并发、线程或其他进程将这个文件描述符共享到这个临时文件,我仍然没有看到竞争条件的可能性,也许是这个概念不完整的逻辑事务,但可以将其检测并清除.

Given that there isn't any mention of concurrency, threading or other processes sharing this file descriptor to this temp file, I still don't see the possibility for a race condition, maybe the concept of an incomplete logical transaction, but that can be detected and cleaned up.

要绝对确保清除所有分配的文件系统资源的正确方法不是仅在应用程序的退出 ,而且在 start-上.我所有的服务器代码都确保在 开始运行之前将其清除并清除自先前的运行.

The correct way to make absolutely sure that any allocated file system resources are cleaned up is not solely on exit of an application but also also on start-up. All my server code, makes sure that everything is cleaned up from a previous run before it starts and makes itself available.

将您的临时文件放在/tmp 的子目录中,以确保您的应用程序在启动和正常关闭时清除该子目录.您可以使用一个Shell脚本来包装您的应用程序启动,该脚本根据 PID 的存在检测到异常关闭( kill -9 ),并清理活动.

Put your temp files in a sub-dir in /tmp make sure your application cleans this sub-dir on startup and normal shutdown. You can wrap your app start up with a shell script that detects abnormal ( kill -9 ) shutdown based on PID existence and also does clean up activities.

这篇关于如何在Linux上创建临时文件,这些临时文件无论如何都会自动清除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆