Apr 30, 2012

C Program to lock file using semaphores.

Write a C Program to lock file using semaphores.
Using semaphores, We can control access to files, shared memory and other things. The basic functionality of a semaphore is that you can either set it, check it, or wait until it clears then set it ("test-n-set"). In C semaphores functions defined in the sys/sem library. Read more about C Programming Language . and read the C Programming Language (2nd Edition) by K and R.



/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/

 

#include <stdio.h>
#include <sys/file.h>
#include <error.h>
#include <sys/sem.h>
#define MAXBUF 100
#define KEY 1216
#define SEQFILE "seq_file"
int semid,fd;
void my_lock(int);
void my_unlock(int);
union semnum
{
    int val;
    struct semid_ds *buf;
    short *array;
}arg;
int main()
{
    int child, i,n, pid, seqno;
    char buff[MAXBUF+1];
    pid=getpid();
    if((semid=semget(KEY, 1, IPC_CREAT | 0666))= = -1)
    {
        perror("semget");
        exit(1);
    }
    arg.val=1;
    if(semctl(semid,0,SETVAL,arg)<0)
    perror("semctl");
    if((fd=open(SEQFILE,2))<0)
    {
        perror("open");
        exit(1);
    }
    pid=getpid();
    for(i=0;i<2;i++)
    {
        my_lock(fd);
        lseek(fd,01,0);
        if((n=read(fd,buff,MAXBUF))<0)
        {
            perror("read");
            exit(1);
        }
        printf("pid:%d, Seq no:%d\n", pid, seqno);
        seqno++;
        sprintf(buff,"%d\n", seqno);
        n=strlen(buff);
        lseek(fd,01,0);
        if(write(fd,buff,n)!=n)
        {
            perror("write");
            exit(1);
        }
        sleep(1);
        my_unlock(fd);
    }
}
void my_lock(int fd)
{
    struct sembuff sbuf=(0, -1, 0);
    if(semop(semid, &sbuf, 1)= =0)
    printf("Locking: Resource…\n");
    else
    printf("Error in Lock\n");
}
void my_unlock(int fd)
{
    struct sembuff sbuf=(0, 1, 0);
    if(semop(semid, &sbuf, 1)= =0)
    printf("UnLocking: Resource…\n");
    else
    printf("Error in Unlock\n");
} 
Read more c programs
C Basic
C Strings
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!



To browse more C Programs visit this link