C program on fcntl system call usage with flag F_GETFL
/* F_GETFL in fcntl return
positive integer if the First arguemnt
entered into
"fcntl is a valid FD. It returns -1, if the FD is an invalid FD.
*/
/* In the below program File Descriptors 0, 1 and 2 are stdout, stdin and stderr.
3 is the FD
for newly created file "file.txt", which is also a valid FD. So,
FD's beyond 4
will be invalid and this can be detected using fcntl function call
with 2nd
arguement set to F_GETFL */
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
int main()
{
FILE * fp;
fp = fopen
("file.txt", "w+");
if (fp != NULL)
{
printf("\n New file descriptor created successfully \n");
}
/* write into file */
fprintf(fp, "%s %s
%s %d", "We", "are", "in", 2012);
int i;
for(i = 0; i< 5;
i++)
{
printf("******************************************************\n");
printf("\n File descriptor entered into fcntl: %d", i);
int
flags;
if((flags
= fcntl(i,F_GETFL,0)) < 0){
perror("fcntl: ");
}
printf("\n return value:%d\n", flags);
printf("******************************************************\n");
}
fclose(fp);
return 0;
}
Output
New file
descriptor created successfully
******************************************************
File descriptor
entered into fcntl: 0
return value:32770
******************************************************
******************************************************
File descriptor
entered into fcntl: 1
return value:32770
******************************************************
******************************************************
File descriptor
entered into fcntl: 2
return value:32770
******************************************************
******************************************************
File descriptor
entered into fcntl: 3
return value:32770
******************************************************
******************************************************
fcntl: : Bad file
descriptor
File descriptor
entered into fcntl: 4
return value:-1
******************************************************