我制作了一个程序,在c程序中锁定咨询文件,下面是我为该任务编写的代码。
#include <stdio.h>
#include <stdlib.h>
#include <sys/file.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
int controller, fsize;
char data[1000], ch;
int fd ;
/* l_type, l_whence, l_start, l_len, l_pid*/
struct flock fl = {F_UNLCK, SEEK_SET, 0, 0, 0};
void Edit();
void Delete();
void Exit();
void Lock();
void main()
{
do
{
clrscr();
fd = open("demo.txt", "w");
FILE *fp = fdopen("demo.txt", "w");
if (fd != NULL)
{
printf("Opening the file!n");
fd = fdopen("demo.txt", "r");
printf("We can open the file in write mode, meaning no other process has lock enabled on it.");
printf("Contents of the file are: nt");
readfile(fd);
fclose(fd);
}
else if ((fd = fopen("demo.txt", "r"))!= NULL)
{
fd = fopen("demo.txt", "r");
printf("We can open the file in read mode, meaning some other process has locked the write permissions on it.");
printf("Contents of the file are: nt");
readfile(fd);
fclose(fd);
}
else
{
printf("File does not exist.n");
}
printf("ntt***** WELCOME USER! THIS IS A SIMPLE TEXT EDITOR *****");
Lock();
Operations();
}
while(1);
}
void Lock()
{
fd = fopen("demo.txt", "w");
fl.l_type = F_RDLCK;
fl.l_pid = getpid();
if (fcntl(fd, F_SETLK, &fl) == -1)
{
printf("Can't set exclusive lockn");
}
else if(fl.l_type!=F_UNLCK)
{
printf("File has been exclusively locked by the process %dn", fl.l_pid);
fl.l_type = F_UNLCK;
printf("File Unlocked! Other processes can execute on the file now.");
}
else
{
printf("File is not lockedn");
}
fclose(fd);
}
void clrscr()
{
system("@cls||clear");
}
void Operations()
{
printf("nntOperations you can perform here:ntn");
printf("nt1.ADD TO FILEnt2.DELETE THE FILEnt3.EXITn");
printf("ntEnter your choice: ");
scanf("%d",&controller);
switch(controller)
{
case 1:
Add();
break;
case 2:
remove("demo.txt");
break;
case 3:
exit(0);
}
}
void Add()
{
fd = fopen("demo.txt", "a");
printf("Enter contents to store in file : n");
fgets(data, 1000, stdin);
fputs(data, fd);
fclose(fd);
printf("Data added to the file successfully");
fd = fopen("demo.txt", "r");
readfile(fd);
fclose(fd);
}
void readfile(FILE *fPtr)
{
char c = getc(fd);
while (c != EOF)
{
printf("%c", c);
c = getc(fd);
}
}
该程序的制作使得每当在另一个进程中再次尝试打开该特定文件时,它都会发出咨询锁定。然而,新用户(来自新流程(可以编辑该文件。
但是程序运行不正常。有人能帮我找出代码中的错误吗。我无法确定我做错了什么?
该程序甚至可以编译吗?咨询锁只是咨询性的,它们不会阻止其他进程打开文件或进行读/写操作。它们只会告诉您何时使用文件描述符是安全的。因此,使用它们的方法是,只有当您真正拥有锁时才进行读/写。
";"安全";在这种情况下,不能有一个通用的答案,这取决于用例。但通常意味着程序员已确保文件在获取之前和释放锁定之后处于一致状态。