Don't use O_DIRECTORY flag, which is Linux specific.

Directories will fail when we try to chdir into them anyway, so all
we lose is the early warning.
(cherry picked from commit fd0488f19bc8325bbb51171dd6fc69b074d2b51c)
Switch back to test folder after each test.

Otherwise the test framework may try to write into the wrong
directory.
(cherry picked from commit 7828a2ad7a4efb1799b8c9208c33e03f3af83aea)
Merge pull request #1124 from kacfengine/safe_open_3.5.x

[3.5.x] Some fixes for the safe_open() function.