[英]The file locking program is NOT LOCKING FILES
我已經制作了一個程序來鎖定 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: \n\t");
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: \n\t");
readfile(fd);
fclose(fd);
}
else
{
printf("File does not exist.\n");
}
printf("\n\t\t***** 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 lock\n");
}
else if(fl.l_type!=F_UNLCK)
{
printf("File has been exclusively locked by the process %d\n", fl.l_pid);
fl.l_type = F_UNLCK;
printf("File Unlocked! Other processes can execute on the file now.");
}
else
{
printf("File is not locked\n");
}
fclose(fd);
}
void clrscr()
{
system("@cls||clear");
}
void Operations()
{
printf("\n\n\tOperations you can perform here:\n\t\n");
printf("\n\t1.ADD TO FILE\n\t2.DELETE THE FILE\n\t3.EXIT\n");
printf("\n\tEnter 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);
}
}
該程序是這樣設計的,當在另一個進程中再次嘗試打開該特定文件時,它會發出建議鎖定。 然后,新用戶(來自新進程)可以編輯該文件。
但程序運行不正常。 誰能幫我找出代碼中的錯誤。 我無法確定我做錯了什么?
該程序甚至可以編譯嗎? 咨詢鎖只是咨詢性的,它們不會阻止其他進程打開文件或進行讀/寫。 它們只會告訴您何時可以安全使用文件描述符。 因此,使用它們的方法是僅在您實際擁有鎖時才進行讀/寫。
在這種情況下,“安全”的含義不能有一個通用的答案,它取決於用例。 但通常意味着程序員已確保文件在獲取鎖之前和釋放鎖之后處於一致的 state 中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.