Reputation: 1
I tried to lock-unlock file in c. If the file is exist then there is no problem but if file does not exist and file is created, file stays locked. If I tried to open the file, It did not open. It says "there is no permission to open". Let's say file is: hey.txt, If it is exist there is no problem I can open this. But if hey.txt is not exist, file will created and write is done succesfully but I cannot open the file. I can only see file content when I wrote this sudo cat hey.txt to terminal
#define WRITE_FLAGS (O_WRONLY | O_CREAT | O_APPEND) //Write flag
int main(int argc , char* argv[]){
struct flock lock;
int fd=open(argv[0],WRITE_FLAGS);
int result_of_fcntl=0;
if(fd==-1){
perror("The file cannot opened.\n");
return-1;
}
memset(&lock,0,sizeof(lock));
lock.l_type=F_WRLCK;
result_of_fcntl=fcntl(fd,F_SETLKW,&lock);
char buffer2[]={"deneme\n"};
int byteswritten = write(fd,buffer2,7);
if(byteswritten==-1){
perror("Error while writing to file:");
return -1;
}
//unlock
lock.l_type=F_UNLCK;
result_of_fcntl=fcntl(fd,F_SETLKW,&lock);
if(result_of_fcntl==-1){
perror("Error:");
return -1;
}
int closeFlag= close(fd);
if(closeFlag==-1){
perror("The file cannot closed.\n");
return-1;
}
return 0;
}
Upvotes: 0
Views: 590
Reputation: 162164
Your problem is not file locking, but improperly set file permission bits at reation time. Change your call to open
like this:
open(filename, O_CREAT, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
Upvotes: 5