Why an open descriptor is not closed on program exit?
I have a small program below on 2.6.16-rc3, which uses busy box (on jffs2 file system). If I run the program multi开发者_如何学Cple times, it starts to fail second time onwards . When the program quits, the descriptors shall be auto closed and next time it shall start fresh , right ?
Why I am getting -1 some times? (Note - On my Fedora Linux PC , it works fine)
root@badge 07:29:32 ~ >touch Hello.txt
root@badge 07:29:37 ~ >./a.out
FP = 3
root@badge 07:29:38 ~ >./a.out
FP = -1
root@badge 07:29:40 ~ >./a.out
FP = 3
root@badge 07:29:41 ~ >./a.out
FP = -1
root@badge 07:29:42 ~ >./a.out
FP = 3
root@badge 07:29:43 ~ >./a.out
FP = 3
root@badge 07:29:43 ~ >./a.out
FP = -1
root@badge 07:29:45 ~ >
Program:
#include <stdio.h>
int main()
{
int fp;
fp = open ("Hello.txt");
printf("FP = %d\n", fp);
return 0; // No close() is used. On exit, it shall be closed.
}
Text File:
-rw-r--r-- 1 root root 0 Sep 20 07:22 Hello.txt
You're not following the contract of the open()
call. The man page (on Linux) states this:
SYNOPSIS
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
int creat(const char *pathname, mode_t mode);
As you can see, you're forgetting to include the right headers, and open()
also takes a flags parameter where you would state read/write rights, etc. As this is laid out you'll get a mystery argument passed to open()
, this is whatever was on the stack or in the registers at the time.
精彩评论