You might not have permission to write to the file.
The system call to chmod swallows up any error messages, and will not report the output to any error log. You are better off using the perl chmod command because it will complain when it has trouble.
It is feasible that your code could create a file to which it can not write. You need to check not only the resulting permissions on the file, but the immediate parent directory as well, assuming it exists.
UPDATE: What I mean is that you might have all the permissions turned on, but the wrong user owns the file. It looks like due-diligence on your part, so I'm just throwing stuff out there.