Search code examples
pythoneofioctlfcntl

How to write EOF markers on Magnetic Tape - Python


I have searched a great deal on the web and I am unable to find a way to write an EOF marker on a magnetic tape in Python.

I have the below code (using Python via fcntl.ioctl) which writes records but after each os.write it does not write an EOF but keeps the records on a single file. Essentially I would like to split those records into files with EOF markers in between?

Code:

import os
import struct
import fcntl

MTIOCTOP = 0x40086d01  # Do a magnetic tape operation
MTSETBLK = 20
TAPEDRIVE = '/dev/st1'

fh = os.open(TAPEDRIVE, os.O_WRONLY )
fcntl.ioctl(fh, MTIOCTOP, struct.pack('hi', MTSETBLK, 0))
os.write(fh, b'a'*1024)                                      #<- Does not add EOF mark after write
fcntl.ioctl(fh, MTIOCTOP, struct.pack('hi', MTSETBLK, 0))
os.write(fh, b'b'*2048)
fcntl.ioctl(fh, MTIOCTOP, struct.pack('hi', MTSETBLK, 0))
os.write(fh, b'c'*1024)
fcntl.ioctl(fh, MTIOCTOP, struct.pack('hi', MTSETBLK, 0))
os.write(fh, b'd'*2048)
os.close(fh)

Tape analysis:

Commencing Reading Tape in Drive /dev/st1, blocksize = 32768
1024 2048 1024 2048
End of File Mark after 4 records
End of File Mark after 0 records
End of Tape
Tape Examination Complete, found 2 Files on tape`

I have noticed that mtio.h contains MTWEOF here but I am not sure how to implement this via ioctl?

Any help would be greatly appreciated.

PS. I am aware I can write EOF marks using mt -f /dev/st1 weof n# but I prefer to keep this within Python only.


Solution

  • Ok so after reading through the mtio.h man pages I worked it out and hopefully it can be of some help to others.

    import os
    import fcntl
    import struct
    
    MTIOCTOP    = 0x40086d01  # Do a magnetic tape operation refer to mtio.h 
    #MTSETBLK   = 20          # Set a block size?
    MTWEOF      = 5           # Define EOF mark variable refer to mtio.h 
    TAPEDRIVE   = '/dev/st1'  # Tape drive location
    
    fd = os.open(TAPEDRIVE, os.O_WRONLY )                          # Open device for write   
    #fcntl.ioctl(fd, MTIOCTOP, struct.pack('hi', MTSETBLK, 32768)) # Set a block size?
                      
    for _ in range(5):                                            
        os.write(fd, b'a'*1024)                                    # Write some bytes
        fcntl.ioctl(fd, MTIOCTOP, struct.pack('hi', MTWEOF, 1))    # Write end-of-file (1)
    
    fcntl.ioctl(fd, MTIOCTOP, struct.pack('hi', MTWEOF, 2))        # Write end-of-tape (2)
    os.close(fd)
    

    Tape analysis

    Commencing Reading Tape in Drive /dev/st1, blocksize = 32768
    1024 1024 1024 1024 1024 
    End of File Mark after 1 records
    End of File Mark after 1 records
    End of File Mark after 1 records
    End of File Mark after 1 records
    End of File Mark after 1 records
    End of Tape
    Tape Examination Complete, found 5 Files on tape