'Shell redirection doesn't move file position for stdout
I have a minimal complete example where the Linux API behavior seems to be a bit ambiguous. The stdout is closed, reopened and used as a regular file's descriptor:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int main(void) {
system("echo > testfile");
fclose(stdout);
int fd = open("testfile", O_WRONLY);
if (fd < 0) {
perror("open():");
return -1;
}
dprintf(fd, "Test\n");
system("echo Test2");
system("echo TestFFFFFFFFFFFF >> /proc/$$/fd/1"); // problem line
sleep(5);
dprintf(fd, "Test4\n");
system("echo Test5");
return 0;
}
Before sleep in testfile I see
Test
Test2
TestFFFFFFFFFFFF
But after sleep this line is overwritten:
Test
Test2
Test4
Test5
FFFF
It seems that for regular files this behavior is strange: if we write something to file - we change its position an appropriate way (to the end).
But for stdout it looks quite reasonable: if we write to stdout - we rewind its position back after finish writing (to the start).
Is this a bug or the right way?
P.S. Besides the bash I also tried dash and ksh - the same thing.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
