Applying lock on a file in Unix Ksh

Hi,

How can we apply lock on a text file through Unix Ksh script. I did found a command flock (file descriptor) but am not very acquainted with the usage.

Can anybody tell me if I need to use Flock command for applying locks to a file while writing on it. If the person can explain the usage with an example, that will be really great.

If this is not the right command, can anyone let me know what command shall i use.

lockfile:-
This utility is part of the procmail package (www.procmail.org). It creates a lock file, a semaphorefile that controls access to a file, device, or resource. The lock file serves as a flag that this
particular file, device, or resource is in use by a process (it is "busy"), and this permits only restricted
access (or no access) to other processes.
lockfile /home/bozo/lockfiles/$0.lock
# Creates a write-protected lockfile prefixed with the name of the script.
Lock files are used in such applications as protecting system mail folders from simultaneously being
changed by multiple users, indicating that a modem port is being accessed, and showing that an
instance of Netscape is using its cache. Scripts may check for the existence of a lock file created by a
certain process to check if that process is running. Note that if a script attempts to create a lock file
that already exists, the script will likely hang.
Normally, applications create and check for lock files in the /var/lock directory.
A script can test for the presence of a lock file by something like the following.
appname=xyzip
# Application "xyzip" created lock file "/var/lock/xyzip.lock".
if [ -e "/var/lock/$appname.lock" ]
then #+ Prevent other programs & scripts
# from accessing files/resources used by xyzip.
...


flock:-

Much less useful than the lockfile command is flock. It sets an "advisory" lock on a file and then
executes a command while the lock is on. This is to prevent any other process from setting a lock on
that file until completion of the specified command.
flock $0 cat $0 > lockfile__$0
# Set a lock on the script the above line appears in,
#+ while listing the script to stdout.
Unlike lockfile, flock does not automatically create a lock file.

Thanks Ahmad!!!!!

I will test it and will inform you if it worked.

Here is a pointer to a good discusion on the issue: create/remove a lock file