Quote:
Originally Posted by blowtorch
However, for reasons not really known to me (not a FreeBSD regular), the file was truncated every time it was 'open'ed, so I always got only 6 chars in the file.
Apart from that, it works just like you want.
That lseek should be using symbolic constants, but it is probably equivalent to
lseek(desc,SEEK_SET,sizeof(char))
Why on Earth we are seeking to sizeof(char) I cannot say. But sizeof(char) is normally 1. So we move the current pointer from 0 to 1 and start writing. If you then write 6 characters, you will have a 7 character file and the first character will be null. Without that lseek, this would be equivalent to
echo "ababab\c" > file
(Or: echo -n "ababab" depending on your style of echo)
Repeatedly doing that doesn't result in a longer file, but you're not really truncating, you're overwriting. You could add "O_APPEND" to the open flags. That is like:
echo "ababab\c" >> file
Another approach would be to use lseek to move to the end of file prior to writing: lseek(desc, SEEK_END,0)
While I'm commenting on this, the results of code like this is not predictable. You are depending on the parent to reach the write first. There is no guarantee that this will be the case.