3.7 File Sharing

Any program can share its open files with any other program. By default, the system permits programs to open and modify a file even if another program has the file open already. Because unrestricted file sharing can lead to such problems as one program writing over the data another program is trying to read, MS-DOS provides file-sharing modes that restrict access to open files, as well as a file-locking function that enables one program to temporarily deny other programs access to one or more regions (consecutive bytes) of a file.

File-sharing mode determines whether a file can be opened by more than one program at a time. When a program opens a file by using Open File with Handle (Interrupt 21h Function 3Dh), it can set the file-sharing mode to one of the following:

Mode Description

OPEN_SHARE_COMPATIBILITY (000h) Allows other programs full access to the file.
OPEN_SHARE_DENYREADWRITE (0010h) Prevents other programs from opening the file.
OEPN_SHARE_DENYWRITE (0020h) Permits other programs to open the file for reading but not for writing.
OPEN_SHARE_DENYREAD (0030h) Permits other programs to open the file for writing but not for reading.
OPEN_SHARE_DENYNONE (0040h) Permits other programs to open the file for reading and writing, but not for compatibility access.

In general, programs that access files across a network or that leave files open while running child programs should deny other programs access to those files, to prevent unexpected changes to them. Some programs, however, are designed to share their open files and must not deny access to them. These programs can prevent unexpected changes by using Lock/Unlock File (Interrupt 21h Function 5Ch) to lock one or more regions of the file.

When a region is locked, other programs can open the file but cannot access the locked region. Attempting to do so returns a lock-violation error. The program that locks a region can also unlock it by using Lock/Unlock File.

In general, a program that locks regions should unlock them as soon as possible, to keep other programs from waiting unnecessarily. To enhance the performance of programs that lock regions, MS-DOS automatically retries access to a locked region several times before returning the lock-violation error. This reduces the number of times a program must retry access on its own. A program can set the number of retries MS-DOS is to attempt by using Set Sharing Retry Count (Interrupt 21h Function 440Bh).

File-sharing modes and file locking are available on a local computer only if the Share program is loaded. A program can determine whether Share is loaded by using Get SHARE.EXE Installed State (Interrupt 2Fh Function 10h). If Share is loaded, this function clears the carry flag and sets the AL register to 0FFh.