Andrey Isakov
Andrey Isakov

Reputation: 1

opening descriptor and closing , why does it matter?

i have the following code it prints to the screen: haha to the file :

haha
hello
Father finished

if i remove line 6 and 7 , I get different results why?

int main()
{
// creates a new file having full read/write permissions
int fd = open("myfile", O_RDWR|O_CREAT, 0666);
write(fd, "haha\n", 5);
close(fd);                  // line 6
fd = open("myfile", O_RDWR);        // line 7
close(0);
close(1);
dup(fd);
dup(fd);
if (fork() == 0)
{
    char s[100];
    dup(fd);
    scanf("%s", s);
    printf("hello\n");
    write(2, s, strlen(s));     
    return 0;                   
}
wait(NULL);
printf("Father finished\n");
close(fd);
return 0;
}

Upvotes: 0

Views: 107

Answers (2)

sukumarst
sukumarst

Reputation: 275

Try to comment out the scanf(), recompile and rerun. The scanf() trying to read beyond EOF might be doing something in the stdio library internal buffers that is causing this issue in printf() buffer not being flushed at the time of process _exit. Just a guess...

Upvotes: 1

Joni
Joni

Reputation: 111219

A file descriptor has only one position which is used both for writing and reading. When you write to the file in line 4 the position is advanced past what was just written, so the descriptor's position is at the end of the file. Calling close and open has the effect of resetting the position to the beginning of file (among other things).

You could replace the calls to close and open with lseek(fd, 0, SEEK_SET) to have the same effect, without closing and reopening the file.

Also, you should not mix the stdio functions scanf, printf and low level functions such as write. The results of the program will be unpredictable because of buffering in the stdio functions.

Upvotes: 0

Related Questions