Program:
#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
void main()
{
int fd=open("b.txt",O_RDONLY);
fchmod(fd,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH);
}
Output:
$ ls -l b.txt
----r----- 1 mohanraj mohanraj 0 Sep 12 15:09 b.txt
$ ./a.out
$ ls -l b.txt
----r----- 1 mohanraj mohanraj 0 Sep 12 15:09 b.txt
$
For the above program, My expected output is to set the permission for b.txt as "rw_rw_r__". But, It still remains in the old permission. Why it will be like this. Is this code have any bug ?
You don't have permission to modify the file, call your program with sudo to have it succeed.
Also always check the return value of functions like open and fchmod and handle the errors .
First of all you should check if fd returned by open syscall is fine and you should check fchmod syscall status as well.
Secondly, I tested your example code and in my case it works as follows.
Before running your program:
pi@raspberrypi ~ $ ls -l hej.txt
-rw-r--r-- 1 pi pi 0 Sep 12 11:53 hej.txt
After running your program:
pi@raspberrypi ~ $ ls -l hej.txt
-rwxrwxrw- 1 pi pi 0 Sep 12 11:53 hej.txt
Your program might missing permission to this file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With