File Copy
Open src mmf with read and create dest mmf with read/write.
proc FileCopy {src dest} {
set mmf(0) [mmf::create $src {generic_read} {
share_read} {open_existing} {attribute_normal}]
set mmf(1) [mmf::create $dest {generic_read
generic_write} {share_read share_write} {
create_always} {attribute_normal}]
Create two maps one for readonly and another for readwrite.
[$mmf(0) length] returns low and high 32-bit pair of length.
Here we are supposed that the file size is less than 2GB.
set len [lindex [$mmf(0) length] 0]
set map(0) [$mmf(0) map {page_readonly} 0 0 "MMF"]
set map(1) [$mmf(1) map {page_readwrite} $len 0]
Create views with offset 0 and size 0 which maps whole file.
set view(0) [$map(0) view {map_read} 0 0 0]
set view(1) [$map(1) view {map_write} 0 0 0]
Copy one file to another
set s [$view(0) get binary 0 $len]
$view(1) put binary $s 0
Close two views, maps, and mmfs
$view(1) close
$view(0) close
$map(1) close
$map(0) close
$mmf(1) close
$mmf(0) close
}
Shared Data Among Processes
MMF can be used to share memory among processes.
Following example demonstrate that a Tk process sends a text from a dialog box and another Tk process receives that data from the shared memory.
First process to write on shared memory
loads mmf package and sets windows size
package require mmf
wm geometry . 160x60+480+100
creates a memory mapping object with read/write and size 4K with name "SharedMemory".
set m [mmf::memory {page_readwrite} 4096 0 "SharedMemory"]
creates a memory view with read and write for entire memory mapping object set by size 0
set v [$m view {map_read map_write} 0 0 0]
creates entry widget
entry .field -textvariable s -relief sunken
creates send button. click it will put entry variable s to the view.
frame .f
button .f.send -text Send -command {
$v put string $s 0}
button .f.close -text Close -command {
$v close; $m close; exit}
pack entry and buttons
pack .f.send .f.close -side left -padx 2 -pady 2
pack .field .f -padx 4 -pady 2
Second process to read shared memory
loads mmf package and sets windows size
package require mmf
wm geometry . 160x60+300+100
opens a created memory mapping object with read/write and name SharedMemory
set m [mmf::open {map_read map_write} 0 "SharedMemory"]
creates a view with read and write for entire memory mapping object set by size 0
set v [$m view {map_read map_write} 0 0 0]
creates entry widget
entry .field -textvariable s -relief sunken
creates receive and close buttons. Gets string from shared view.
frame .f
button .f.send -text Receive -command {
set s [$v get string 0 4096]}
button .f.close -text Close -command {
$v close; $m close; exit}
pack entry and buttons
pack .f.send .f.close -side left -padx 2 -pady 2
pack .field .f -padx 4 -pady 2