Copyright (c) Hyperion Entertainment and contributors.

Difference between revisions of "Cooperative Record Locking"

From AmigaOS Documentation Wiki
Jump to navigation Jump to search
Line 130: Line 130:
   
 
<syntaxhighlight>
 
<syntaxhighlight>
; /* LockRecord.c - Execute me to compile me with SAS/C 6.56
+
// LockRecord.c
  +
//
sc NMINC STRMERGE NOSTKCHK NODEBUG DATA=FAR IGNORE=73 LockRecord.c
 
slink FROM LockRecord.o to LockRecord LIB lib:amiga.lib
+
// LockRecord()/UnLockRecord() example.
quit
 
*
 
* AmigaMail LockRecord()/UnLockRecord() example.
 
*/
 
 
/*
 
(c) Copyright 1992-1999 Amiga, Inc. All rights reserved.
 
The information contained herein is subject to change without notice,
 
and is provided "as is" without warranty of any kind, either expressed
 
or implied. The entire risk as to the use of this information is
 
assumed by the user.
 
*/
 
   
 
#include <exec/memory.h>
 
#include <exec/memory.h>

Revision as of 23:14, 14 March 2013

Description

The Amiga's cooperative record locking scheme allows an application to lock regions of a file rather than locking an entire file. These regions are known as records.

The Amiga thinks of a record in terms of size and offset. The size refers to the length of the record in bytes. The offset refers to the starting position of the record from the beginning of the file. The size and offset can vary from record to record. The only limit on a record's size and offset are the limits the file system has on the size of the file.

Record Lock Types

There are two basic types of record lock, exclusive and shared. An exclusive lock gives an application exclusive access to a record. While an application holds an exclusive record lock, no other process can obtain a record lock that overlaps the exclusively locked region. The file system can only grant an exclusive record lock on a region that is not part of an existing record lock.

The other type of record lock, the shared lock, gives an application shared access to a record. While an application holds a shared record lock, other applications can also obtain a shared record lock that overlaps the original shared record lock, but no other process can obtain an exclusive record lock that overlaps the shared record lock.

Locking and Unlocking Records

To lock (or unlock) a record within a file, an application needs a valid file handle on the file. Two DOS Library functions handle individual record locks:

BOOL LockRecord(BPTR myFH, ULONG my_offset, ULONG my_length, ULONG my_mode, ULONG my_timeout);
BOOL UnLockRecord(BPTR myFH, ULONG my_offset, ULONG my_length);

In both functions, the myFH field refers to the valid file handle mentioned above, and the my_offset and my_length fields refer to the record's offset and size.

The LockRecord() function has two additional parameters: my_mode and my_timeout. The my_mode field refers to the type of record. DOS supports four record types:

REC_EXCLUSIVE
Create an exclusive record lock. If the record is not immediately available, the file system will make a second record lock attempt when the timeout expires. The timeout (the my_timeout field from the RecordLock() prototype above) is in DOS ticks (1/50 of a second).
REC_EXCLUSIVE_IMMED
This record type is like REC_EXCLUSIVE, but the attempt to lock a record will fail if the record is not immediately available. In this case the file system ignores the timeout.
REC_SHARED
Create a shared record lock. If the record is not immediately available, the file system will make a second record lock attempt when the timeout expires. The timeout (the my_timeout field from the RecordLock() prototype above) is in DOS ticks (1/50th of a second).
REC_SHARED_IMMED
This record type is like REC_SHARED, but the attempt to lock a record will fail if the record is not immediately available. In this case the file system ignores the timeout.

The Amiga record locking scheme is cooperative--the file system does not prevent any process from accessing any part of a data file. The record locking scheme has nothing to do with other actions of a file system. The file system will let other processes read and write a data file regardless of any existing record locks on the data file.

Also, when an application attempts to create a record lock, the file system's record locking mechanism only makes sure the record won't conflict with any existing record locks on the same data file. The file system doesn't check the validity of the locked region. This makes it possible to lock records in an empty data file and also to lock records that are well beyond the end of a data file. This feature may be useful to an application that needs to lock records that don't exist yet.

When releasing a record lock, an application must provide exactly the same parameters it used when it locked the record. Attempting to unlock a record using a different offset or length will fail. If the application does not successfully unlock a record, the record lock will remain in effect. This means further requests to lock that record can fail, depending on the type of record lock. The record lock will remain in effect until the data file is removed or the system restarted. As with most Amiga resources, an application should release a record lock as quickly as possible. This helps out other applications that might be waiting to access the locked record.

Locking Multiple Records

DOS Library offers a function to lock an array of record locks:

BOOL LockRecords(struct RecordLock *recordarray, ULONG multi_timeout);

LockRecords() locks a group of records using one function call. LockRecords() accepts a pointer to an array of RecordLock structures (as defined in <dos/record.h>):

struct RecordLock {
        BPTR    rec_FH; /* The file handle of the data file */
        ULONG   rec_Offset;     /* The record offset in the data file */
        ULONG   rec_Length;     /* The length of the record */
        ULONG   rec_Mode;       /* The mode of the record lock */
};

The fields in each RecordLock structure correspond to the parameters from the LockRecord() function. The records do not have to be in the same file. The array is terminated by a dummy RecordLock with a NULL file handle (rec_FH).

The RecordLock structure does not include a timeout. Instead, LockRecords() applies the same timeout (multi_timeout from the LockRecords() prototype above) to each RecordLock in the array. If LockRecords() fails to lock any of the records in its array, LockRecords() releases any successful record locks from the array, and return DOSFALSE.

To unlock records locked by LockRecords(), use the dos.library function UnLockRecords():

BOOL UnLockRecords(struct RecordLock *recordarray);

This function accepts the same array used to lock the records with LockRecords().

Note that it is possible to use UnLockRecord() on a record locked by LockRecords(). However, if an application uses UnLockRecord() to unlock one record in the RecordLock array, it should use UnLockRecord() to unlock all of the records in the array.

Locking Records Using DOS Packets

Don't use DOS Packets
DOS Library now handles record locking as of version 53.?? so that file systems are no longer burdened with implementing this functionality. The information below is being provided for reference and for users of previous versions of the DOS Library.

To lock a record using the DOS packet interface, send an ACTION_LOCK_RECORD (2008) packet to the file system. This packet uses the following arguments:

ARG1: BTPR   The file handle of the data file in which you wish to lock a record.
ARG2: ULONG  The offset (in bytes) in the file of the record.
ARG3: ULONG  The length (in bytes) of the record.
ARG4: ULONG  The mode with which you wish to lock record.
ARG5: ULONG  Time (in ticks) you are will to wait for the record to become available.

RES1: BOOL   Upon return RES1 will contain the success/failure status:
             DOSTRUE if the record lock was successfully locked.
             DOSFALSE if the record lock failed.
RES2: CODE   Failure code if the record lock failed for a reason other than denied
             access (collision for example).

To unlock a record using the DOS packet interface, send an ACTION_FREE_RECORD (2009) packet. This packet uses the following arguments:

ARG1: BPTR   The file handle of the data file in which you locked the record.
ARG2: ULONG  The offset (in bytes) in the file of the record with which you locked
             the record.
ARG3: ULONG  The length (in bytes) of the record with which you locked the record.

RES1: BOOL   Upon return RES1 will contain the success/failure status:
             DOSTRUE if the record lock was successfully unlocked.
             DOSFALSE if there was no lock to unlock.
RES2: CODE   Possible failure code if the record lock could not be unlocked.

Examples

LockRecord.c

// LockRecord.c
//
// LockRecord()/UnLockRecord() example.
 
#include <exec/memory.h>
#include <exec/lists.h>
#include <dos/dosextens.h>
#include <dos/rdargs.h>
#include <dos/record.h>
#include <utility/tagitem.h>
 
#include <clib/alib_protos.h>
#include <clib/dos_protos.h>
#include <clib/exec_protos.h>
#include <clib/utility_protos.h>
 
void GetCommandLine(BPTR, struct RDArgs *rdargs, UBYTE *cmdbuffer);
void DoLockRecord(BPTR, struct RDArgs *rdargs);
void DoUnLockRecord(BPTR fh, struct RDArgs *rdargs);
void ListRecordLocks(void);
struct LockNode *FindRecordLock(ULONG offset, ULONG length);
 
/* List and node structures to keep track of record locks */
struct LockNode {
    struct LockNode *ln_Succ;
    struct LockNode *ln_Pred;
    ULONG ln_Counter;
    ULONG ln_Offset;
    ULONG ln_Length;
    ULONG ln_Mode;
};
 
struct LockList {
    struct LockNode *lh_Head;
    struct LockNode *lh_Tail;
    struct LockNode *lh_TailPred;
    ULONG lh_Counter;
};
 
/* Pseudo data file */
#define TESTFILE "t:locktest"
 
#define LOCK_TEMPLATE "OFFSET/K/N,LENGTH/K/N,EXCLUSIVE/S,IMMEDIATE/S,TIMEOUT/K/N"
#define UNLOCK_TEMPLATE "OFFSET/K/N,LENGTH/K/N"
 
#define OFFSET_POS      0
#define LENGTH_POS      1
#define EXCLUSIVE_POS   2
#define IMMEDIATE_POS   3
#define TIMEOUT_POS     4
 
struct Library *SysBase;
struct DosLibrary *DOSBase;
struct Library *UtilityBase;
 
struct LockList *locklist;
 
LONG main(void)
{
    BPTR fh;
    struct RDArgs *rdargs;
    struct CSource *csource;
    UBYTE *cmdbuffer;
    struct LockNode *lnode, *nnode;
    LONG error = RETURN_OK;
 
    SysBase = (*((struct Library **) 4));
 
    /* Fails silently if < 37 */
    if (DOSBase = (struct DosLibrary *)OpenLibrary("dos.library", 37))
    {
        UtilityBase = DOSBase->dl_UtilityBase;
 
        if (locklist = AllocMem(sizeof(struct LockList), MEMF_CLEAR))
        {
            NewList((struct List *)locklist);
 
            /* Allocate RDArgs structure to parse command lines */
            if (rdargs = AllocDosObject(DOS_RDARGS, TAG_END))
            {
                csource = &rdargs->RDA_Source;
 
                /* Get buffer to read command lines in */
                if (csource->CS_Buffer = AllocMem(512, MEMF_CLEAR))
                {
                    csource->CS_Length = 512;
                    csource->CS_CurChr = 0;
 
                    /* Buffer to isolate command keyword */
                    if (cmdbuffer = AllocMem(80, MEMF_CLEAR))
                    {
 
                        /* Open a testfile, create it if necessary */
                        if (fh = Open(TESTFILE, MODE_READWRITE))
                        {
 
                            /* Process command lines */
                            GetCommandLine(fh, rdargs, cmdbuffer);
 
                            /* Try to get rid of outstanding record locks */
                            lnode = locklist->lh_Head;
                            while (nnode = lnode->ln_Succ)
                            {
 
                                /* Try to unlock pending locks */
                                if ((UnLockRecord(fh,
                                                  lnode->ln_Offset,
                                                  lnode->ln_Length)) == DOSFALSE)
                                {
                   Printf("Error unlocking record %ld with offset %ld length %ld\n",
                                        lnode->ln_Counter,
                                        lnode->ln_Offset,
                                        lnode->ln_Length);
                                    if (IoErr())
                                        PrintFault(IoErr(), NULL);
                                }
                                /* Remove node no matter what */
                                FreeMem(lnode, sizeof(struct LockNode));
                                lnode = nnode;
                            };
 
                            Close(fh);
                        }
                        FreeMem(cmdbuffer, 80);
                    } else
                        SetIoErr(ERROR_NO_FREE_STORE);
 
                    FreeMem(csource->CS_Buffer, 512);
                } else
                    SetIoErr(ERROR_NO_FREE_STORE);
 
                FreeDosObject(DOS_RDARGS, rdargs);
            } else
                SetIoErr(ERROR_NO_FREE_STORE);
 
            FreeMem(locklist, sizeof(struct LockList));
        } else
            SetIoErr(ERROR_NO_FREE_STORE);
 
 
        error = IoErr();
        if (error)
        {
            PrintFault(IoErr(), NULL);
            error = RETURN_FAIL;
        }
 
        CloseLibrary((struct Library *)DOSBase);
    }
    return(error);
}
void GetCommandLine(BPTR fh, struct RDArgs *rdargs, UBYTE *cmdbuffer)
{
    struct CSource *csource = &rdargs->RDA_Source;
    UBYTE *cmdlinebuffer = csource->CS_Buffer;
    LONG error;
 
    /* Prompt for command line */
    Write(Output(), "Cmd> ", 5);
 
    /* Loop forever, waiting for commands */
    for (;;)
    {
        /* Get command line */
        if ((FGets(Input(), cmdlinebuffer, 512)) != NULL)
        {
 
            /* Use ReadItem() to isolate actual command */
            error = ReadItem(cmdbuffer, 80, csource);
 
            /* Break on error */
            if (error == ITEM_ERROR)
                break;
 
            /* Make sure I've got something */
            else if (error != ITEM_NOTHING)
            {
                /* cmdbuffer now contains the command:
                 *
                 * KNOWN COMMANDS:
                 * QUIT
                 * LIST
                 * LOCKRECORD
                 * UNLOCKRECORD
                 */
 
                if ((Stricmp("QUIT", cmdbuffer)) == 0)
                    break;
                else if ((Stricmp("HELP", cmdbuffer)) == 0)
                {
                    Printf("Available commands:\n");
                    Printf("LOCKRECORD %s\n", LOCK_TEMPLATE);
                    Printf("UNLOCKRECORD %s\n", UNLOCK_TEMPLATE);
                    Printf("LIST\n");
                    Printf("QUIT\n");
                }
                else if ((Stricmp("LIST", cmdbuffer)) == 0)
                    ListRecordLocks();  /* Show all current locks */
                else
                {
 
                    /* Note that I've already isolated the command
                     * keyword, so I'm using Source->CS_CurChr to point
                     * after it.
                     */
                    csource->CS_Buffer += csource->CS_CurChr;
                    csource->CS_CurChr = 0;
 
                    if ((Stricmp("LOCKRECORD", cmdbuffer)) == 0)
                        DoLockRecord(fh, rdargs);
                    else if ((Stricmp("UNLOCKRECORD", cmdbuffer)) == 0)
                        DoUnLockRecord(fh, rdargs);
                    else
                        PrintFault(ERROR_NOT_IMPLEMENTED, cmdbuffer);
 
                    /* Reset CSource */
                    csource->CS_Buffer = cmdlinebuffer;
                }
 
                /* Output new prompt. Make sure csource is OK. */
                Write(Output(), "Cmd> ", 5);
                csource->CS_CurChr = 0;
            }
        } else
            break;
    }
}
 
void DoLockRecord(BPTR fh, struct RDArgs *rdargs)
{
    struct RDArgs *readargs;
    LONG rargs[5];
    ULONG offset, length, timeout, mode;
    ULONG result;
    struct LockNode *lnode;
 
    offset = length = timeout = mode = 0;
    rargs[0] = rargs[1] = rargs[2] = rargs[3] = rargs[4] = 0;
 
    if (readargs = ReadArgs(LOCK_TEMPLATE, rargs, rdargs))
    {
 
        if (rargs[OFFSET_POS])
            offset = *((LONG *)rargs[OFFSET_POS]);
        if (rargs[LENGTH_POS])
            length = *((LONG *)rargs[LENGTH_POS]);
        if (rargs[TIMEOUT_POS])
            timeout = *((LONG *)rargs[TIMEOUT_POS]);
 
        /* Type of locking */
        if (rargs[EXCLUSIVE_POS])
        {
            if (rargs[IMMEDIATE_POS])
                mode = REC_EXCLUSIVE_IMMED;
            else
                mode = REC_EXCLUSIVE;
        }
        else
        {
            if (rargs[IMMEDIATE_POS])
                mode = REC_SHARED_IMMED;
            else
                mode = REC_SHARED;
        }
 
        rargs[0] = offset;
        rargs[1] = length;
        switch (mode)
        {
            case REC_EXCLUSIVE_IMMED:
                rargs[2] = (LONG)"REC_EXCLUSIVE_IMMED";
                break;
            case REC_EXCLUSIVE:
                rargs[2] = (LONG)"REC_EXCLUSIVE";
                break;
            case REC_SHARED_IMMED:
                rargs[2] = (LONG)"REC_SHARED_IMMED";
                break;
            case REC_SHARED:
                rargs[2] = (LONG)"REC_SHARED";
                break;
        }
        rargs[3] = timeout;
 
 
        /* Show what I'm going to do */
        VFPrintf(Output(),
            "LockRecord: Offset %ld, Length %ld, Mode %s, Timeout %ld...",
            rargs);
        Flush(Output());
 
        /* Lock the record. Parameters are not checked. It is f.e. possible to
         * specify an offset larger than the size of the file. Possible since
         * Record Locks are not related to the file itself, only the means for
         * you to do arbitration.
         *
         * Note that the timeout value is in ticks...
         */
        result = LockRecord(fh, offset, length, mode, timeout);
 
        if (result == DOSTRUE)
        {
            Write(Output(), "OK\n", 3);
 
            /* Add a node to track this record lock */
            if (lnode = AllocMem(sizeof(struct LockNode), MEMF_CLEAR))
            {
                lnode->ln_Counter = locklist->lh_Counter++;
                lnode->ln_Offset = offset;
                lnode->ln_Length = length;
                lnode->ln_Mode = mode;
 
                AddTail((struct List *)locklist, (struct Node *)lnode);
            }
            else
            {
                /* Not enough memory for node. You're on your own... */
                Write(Output(), "Not enough memory to track record lock.\n", 40);
            }
        }
        else
        {
            Write(Output(), "FAILED\n", 7);
            if (IoErr())
                PrintFault(IoErr(), NULL);
        }
 
        /* Release memory associated with readargs */
        FreeArgs(readargs);
    } else
        PrintFault(IoErr(), NULL);
}
 
void DoUnLockRecord(BPTR fh, struct RDArgs *rdargs)
{
    struct RDArgs *readargs;
    LONG rargs[2];
    ULONG offset, length;
    ULONG result;
    struct LockNode *lnode;
 
    offset = length = 0;
    rargs[0] = rargs[1] = 0;
 
    if (readargs = ReadArgs(LOCK_TEMPLATE, rargs, rdargs))
    {
 
        if (rargs[OFFSET_POS])
            offset = *((LONG *)rargs[OFFSET_POS]);
        if (rargs[LENGTH_POS])
            length = *((LONG *)rargs[LENGTH_POS]);
 
        rargs[0] = offset;
        rargs[1] = length;
 
        /* Show what I'm going to do */
        VFPrintf(Output(), "UnLockRecord: Offset %ld, Length %ld...", rargs);
        Flush(Output());
 
        /* Unlock indicated record with indicated offset and length.
         * If the same record (same offset/length) is locked multiple times,
         * only one, the first one in the list , will be unlocked.
         */
        result = UnLockRecord(fh, offset, length);
 
        if (result == DOSTRUE) {
            Write(Output(), "OK\n", 3);
 
            /* Remove node associated with this lock */
            if (lnode = FindRecordLock(offset, length))
            {
                Remove((struct Node *)lnode);
                FreeMem(lnode, sizeof(struct LockNode));
            }
        }
        else
        {
            Write(Output(), "FAILED\n", 7); /* Keep locknode */
            if (IoErr())
                PrintFault(IoErr(), NULL);
        }
        /* Release memory associated with readargs */
        FreeArgs(readargs);
    } else
        PrintFault(IoErr(), NULL);
}
 
void ListRecordLocks(void)
{
    struct LockNode *lnode;
    LONG rargs[4];
 
    for (lnode = locklist->lh_Head; lnode->ln_Succ; lnode = lnode->ln_Succ)
    {
        rargs[0] = lnode->ln_Counter;
        rargs[1] = lnode->ln_Offset;
        rargs[2] = lnode->ln_Length;
 
        switch (lnode->ln_Mode)
        {
            case REC_EXCLUSIVE_IMMED:
                rargs[3] = (LONG)"REC_EXCLUSIVE_IMMED";
                break;
            case REC_EXCLUSIVE:
                rargs[3] = (LONG)"REC_EXCLUSIVE";
                break;
            case REC_SHARED_IMMED:
                rargs[3] = (LONG)"REC_SHARED_IMMED";
                break;
            case REC_SHARED:
                rargs[3] = (LONG)"REC_SHARED";
                break;
        }
 
        VFPrintf(Output(), "RecordLock #%ld: Offset %ld Length %ld Mode %s\n", rargs);
    }
    Flush(Output());
}
 
struct LockNode *FindRecordLock(ULONG offset, ULONG length)
{
    struct LockNode *lnode;
 
    for (lnode = locklist->lh_Head; lnode->ln_Succ; lnode = lnode->ln_Succ)
    {
        if ((lnode->ln_Offset == offset) && lnode->ln_Length == length)
            return(lnode);
    }
    return(NULL);
}

ExRecLock1.c

// ExRecLock1.c
//
// This is a simple example of using record locking to create an exclusive record
// lock on a file, and writing to that record.  The example ExRecLock2 is almost
// exactly the same as this example, except ExRecLock2 uses the record lock directly
// after ExRecLock1's record.  If you try to run ExRecLock1 (or ExRecLock2) while
// another instance of ExRecLock1 (or ExRecLock2) is running, the second record lock
// attempt will fail.
 
#include <clib/dos_protos.h>
#include <clib/alib_protos.h>
#include <clib/alib_stdio_protos.h>
 
#define RECORDSIZE   12
#define RECORDOFFSET 0
 
extern struct Library *DOSBase;
 
UBYTE *vers = "\0$VER: ExRecLock1 37.2";
UBYTE *string = "ExRecLock1\n";                           /* This string will be the */
                                                          /* contents of the record. */
void main(void)
{
    BPTR fh;
 
    if (DOSBase->lib_Version >= 37)   /* Record locking was introduced in Release 2, */
    {                                 /* but the standard startup code will open any */
                                      /* version of dos.library, so we have to ex-   */
                                      /* plicitly check the version number of DOS.   */
 
        if (fh = Open("t:testRLock", MODE_READWRITE))     /* Open the file, creating */
        {                                                 /*        it if necessary. */
            if (DOSTRUE == LockRecord(fh,           /* Lock the record as exclusive, */
                                      RECORDOFFSET, /* and do not wait if it is not  */
                                      RECORDSIZE,   /* available immediately.        */
                                      REC_EXCLUSIVE_IMMED, 0))
            {
                LONG error = RECORDOFFSET;
 
                                     /* If the record is beyond the end of the file, */
                if (Seek(fh, 0, OFFSET_END) < RECORDOFFSET)    /* lengthen the file. */
                    error = SetFileSize(fh, RECORDOFFSET, OFFSET_BEGINNING);
 
                if (error == RECORDOFFSET)    /* If there was no error with the file */
                {                             /*                file size, continue. */
                    if (Seek(fh, RECORDOFFSET, OFFSET_BEGINNING) < 0)
                        PrintFault(IoErr(), "Seek() error");
 
                    if (Write(fh, string, RECORDSIZE) < 0)
                        PrintFault(IoErr(), "Write() error");
                    else
                        PutStr("Write successful, ");
                }
                PutStr("Waiting 10 seconds...\n");
                TimeDelay(UNIT_VBLANK, 10, 0);       /* Amiga.lib function that puts */
                          /* a task to sleep for a given amount of time.  This waits */
                          /* 10 seconds before unlocking the record to give the user */
                          /* a chance to start a second copy of this example.        */
                UnLockRecord(fh, RECORDOFFSET, RECORDSIZE);
            }
            else PrintFault(IoErr(), "Record Lock Failed");
            Close(fh);
        }
        else PrintFault(IoErr(), "Open Failed");
    }
    else PutStr("Need dos.library V37 or greater.\n");
}

ExRecLock2.c

// ExRecLock2.c
//
// This is a simple example of using record locking to create an exclusive record
// lock on a file, and writing to that record.  The example ExRecLock1 is almost
// exactly the same as this example, except ExRecLock1 uses the record lock directly
// before ExRecLock2's record.  If you try to run ExRecLock2 (or ExRecLock1) while
// another instance of ExRecLock2 (or ExRecLock1) is running, the second record lock
// attempt will fail.
 
#include <clib/dos_protos.h>
#include <clib/alib_protos.h>
#include <clib/alib_stdio_protos.h>
 
#define RECORDSIZE   12
#define RECORDOFFSET 12
 
extern struct Library *DOSBase;
 
UBYTE *vers = "\0$VER: ExRecLock2 37.2";
UBYTE *string = "ExRecLock2\n";                           /* This string will be the */
                                                          /* contents of the record. */
void main(void)
{
    BPTR fh;
 
    if (DOSBase->lib_Version >= 37)   /* Record locking was introduced in Release 2, */
    {                                 /* but the standard startup code will open any */
                                      /* version of dos.library, so we have to ex-   */
                                      /* plicitly check the version number of DOS.   */
 
        if (fh = Open("t:testRLock", MODE_READWRITE))     /* Open the file, creating */
        {                                                 /*        it if necessary. */
            if (DOSTRUE == LockRecord(fh,           /* Lock the record as exclusive, */
                                      RECORDOFFSET, /* and do not wait if it is not  */
                                      RECORDSIZE,   /* available immediately.        */
                                      REC_EXCLUSIVE_IMMED, 0))
            {
                LONG error = RECORDOFFSET;
 
                                     /* If the record is beyond the end of the file, */
                if (Seek(fh, 0, OFFSET_END) < RECORDOFFSET)    /* lengthen the file. */
                    error = SetFileSize(fh, RECORDOFFSET, OFFSET_BEGINNING);
 
                if (error == RECORDOFFSET)    /* If there was no error with the file */
                {                             /*                file size, continue. */
                    if (Seek(fh, RECORDOFFSET, OFFSET_BEGINNING) < 0)
                        PrintFault(IoErr(), "Seek() error");
 
                    if (Write(fh, string, RECORDSIZE) < 0)
                        PrintFault(IoErr(), "Write() error");
                    else
                        PutStr("Write successful, ");
                }
                PutStr("Waiting 10 seconds...\n");
                TimeDelay(UNIT_VBLANK, 10, 0);       /* Amiga.lib function that puts */
                          /* a task to sleep for a given amount of time.  This waits */
                          /* 10 seconds before unlocking the record to give the user */
                          /* a chance to start a second copy of this example.        */
                UnLockRecord(fh, RECORDOFFSET, RECORDSIZE);
            }
            else PrintFault(IoErr(), "Record Lock Failed");
            Close(fh);
        }
        else PrintFault(IoErr(), "Open Failed");
    }
    else PutStr("Need dos.library V37 or greater.\n");
}