Reputation: 11044
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 ?
Upvotes: 3
Views: 3017
Reputation: 1667
$ ls -l b.txt ----r----- 1 mohanraj mohanraj 0 Sep 12 15:09 b.txt
----r-----, it means owner of b.txt has no Permission to read or write
$chmod 644 b.txt //add read and write Permission, -rw-r--r--
also, change file permission need O_RDWR flag
make sure function success before continue
void main()
{
int fd=open("b.txt",O_RDWR);
if (fd > 0) {
//do some thing
}
}
Upvotes: 0
Reputation: 11044
For file b.txt I didn't set the read permission for owner. So, While we calling the open function, it does not have permission to open b.txt. So, it returns bad file descriptor error. So, it will be like this.
Program:
#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
void main()
{
int fd=open("b.txt",O_RDONLY);
perror("open");
fchmod(fd,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH);
perror("fchmod");
}
Output:
$ ./a.out
open: Permission denied
fchmod: Bad file descriptor
$
Upvotes: 1
Reputation: 1653
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.
Upvotes: 1
Reputation: 145829
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 .
Upvotes: 1