Is there a way to create a tempfile, without having it opened? I have to run an executable, redirect it's output to a file, and then read & parse that. Everything created by tempfile
is already opened, and this triggers an error , because the file is locked.
Asked
Active
Viewed 4,806 times
9

Geo
- 93,257
- 117
- 344
- 520
-
I guess the executable is a separate process which maintains the tempfile opened (locked) while the ruby program is running. Am I right? – Sony Santos Jun 22 '11 at 12:13
-
Yes, Sony Santos. You are right. – Geo Jun 22 '11 at 12:29
5 Answers
24
You can also use Dir::Tmpname
Dir::Tmpname.create('your_application_prefix') { |path| puts path }
path will contain unique path
See https://github.com/ruby/ruby/blob/ruby_1_9_3/lib/tmpdir.rb#L116

timfjord
- 1,759
- 19
- 20
1
I didn't get an error:
Andrew-Grimms-MacBook-Pro:~ agrimm$ irb
>> require "tempfile"
=> true
>> tempfile = Tempfile.new("temporary_file.txt", "/tmp")
=> #<File:/tmp/temporary_file.txt20110622-648-pkynjw-0>
>> tempfile.close
=> nil
>> system("echo foo > #{tempfile.path}")
=> true
>> system("cat #{tempfile.path}")
foo
=> true
>> tempfile.path
=> "/tmp/temporary_file.txt20110622-648-pkynjw-0"
>> exit
Andrew-Grimms-MacBook-Pro:~ agrimm$ cat /tmp/temporary_file.txt20110622-648-pkynjw-0
foo
Then again, the temporary file doesn't seem awfully temporary.
Does the error happen with all programs, or just a specific program? Also, can you post the code that causes the problem, and what error backtrace you get?

Andrew Grimm
- 78,473
- 57
- 200
- 338
-
Andrew, perhaps Windows treats this differently. The error I received was `The process cannot access the file because it is being used by another process` – Geo Jun 22 '11 at 12:33
-
I guess you don't get an error because in your case the process which writes the tempfile is already finished when you try to use the file again. The problem here is that the executable is a separate process which maintains the file opened when the ruby program try to access it. – Sony Santos Jun 23 '11 at 13:01
0
Is using FileUtils.touch acceptable solution? You can touch a file and delete it once you are done with whatever you want.

Miki
- 7,052
- 2
- 29
- 39
-
1#touch isn't too widely acceptable solution because significant advantage of the Dir::Tmpname (and in fact, crucial in most of cases) is the ensured unique filename. – Martin Poljak Nov 05 '13 at 11:45
0
You may want to use pipes.
If the executable is started from your ruby program, consider using IO.popen.
If they're different processes, you can try named pipes.

Sony Santos
- 5,435
- 30
- 41
0
The @timfjord's answer works. But if you don't need a block try:
Dir::Tmpname.create(['prefix-', '.ext']) {}
# => "/tmp/prefix-20190827-1-87n9iu.ext"

fguillen
- 36,125
- 23
- 149
- 210