⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 lock.c

📁 Linux网络编程。主要实现共享资源问题。通过lock()函数实现锁定
💻 C
字号:
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#define SEQFILE "./sequo"
#define MAXBUF 100

main()
{
	int fd,i,n,pid,seqno;
	char buff[MAXBUF+1];
	pid=getpid();
	if ((fd=open("data.txt",O_RDWR|O_CREAT) )<0)
	{
		perror("Can't open");
		exit(1);
	}
	for(i=0;i<5;i++)
	{
		my_lock(fd);
		lseek(fd,01,0);
		if ((n=read(fd,buff,MAXBUF))<=0)
		{
			perror("read error");
			exit(1);
		}
		printf("n=%d  ",n);
		buff[n]=0;
		if (!(n=sscanf(buff,"%d\n",&seqno)))
		{
			perror("sscanf error");
			exit(1);
		}
		printf("pid=%d,seq#=%d\n",pid,seqno);
		seqno++;
		//sprintf(buff,"%03d\n",seqno);
		sprintf(buff,"%d\n",seqno);
		n=strlen(buff);
		lseek(fd,01,0);
		if( write(fd,buff,n)!=n)
		{
			perror("write error");
			exit(1);
		}
		my_unlock();
	}
	close(fd);
}

my_lock(int fd)
{
	lseek(fd,0L,0);
	if (lockf(fd,F_LOCK,0L)==-1)
	{
		perror("can't F_LOCK");
		exit(1);
	}
}
my_unlock(int fd)
{
	lseek(fd,0L,0);
	if(lockf(fd,F_ULOCK,0L)==-1)
	{
		perror("can't F_UNLOCK");
		exit(1);
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -