Issue
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 ?
Solution
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
$
Answered By - mohangraj Answer Checked By - Katrina (WPSolving Volunteer)