0

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;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

2 Answers2

1

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...

sukumarst
  • 265
  • 1
  • 5
0

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.

Joni
  • 108,737
  • 14
  • 143
  • 193
  • ok thanks now understand why there will be no output to the screen. But why the file will contain only the word hahah and not: haha hello Father finished ? – Andrey Isakov Jun 21 '13 at 17:21
  • In my tests it does contain "haha hello Father finished". It's possible that you get different results; mixing stdio with low level io like this leads to unpredictable results. – Joni Jun 21 '13 at 17:35