Saturday, September 1, 2007

shared files program in C

shared files program in C

/* shared file example 1 */


#include <fcntl.h>
#include <stdio.h>


main()
{
int fp;
char buff[20];
fp=open("testfile",O_RDONLY);
if(fork()==0)
{
read(fp,buff,10);
buff[10]=0;
puts(buff);
}

else
{
wait(0);
read(fp,buff,10);
buff[10]=0;
puts(buff);
}

}

/*shared file example 2 */

#include <fcntl.h>
#include <stdio.h>


main()
{
FILE *fp;
char buff[20];
fp=fopen("testfile","r");
if(fork()==0)
{
fgets(buff,10,fp);
buff[10]=0;
puts(buff);
}

else
{
wait(0);
fgets(buff,10,fp);
buff[10]=0;
puts(buff);

}

}

/*lock file */


#include <fcntl.h>
#include <stdio.h>


main()
{
int fd;
fd=open("Lockset",O_RDWR);
lockf(fd,F_LOCK,0);
printf("Process %d locked the file \n",getpid());
if(fork()==0)
{
lockf(fd,F_LOCK,0);
printf("Process %d locked the file \n",getpid());
printf("Child Process is over\n");
}

else
{
sleep(5);
printf("Process %d is over\n",getpid());

}

}

No comments: