If you supply O_CREAT to open(), you must also specify a mode as the third argument. open() is picking up junk and using that as the mode when creating the file, resulting in weird permissions.