2

I am importing some legacy code into an iOS app that uses stdout for some diagnostic output. Of course, iOS does not like you to write to stdout at all, and I need to get that output anyway. I would like to redirect this output to a file, then use the same legacy code again, redirecting the output to a different file. Does anyone know of a way to do this?

I've tried the simplistic

            freopen(p, "w", stderr);

This does work--but only once. After using this call, all output to stdout is forever redirected. That's OK, but subsequent calls to redirect the output to a new location cause system instability that eventually leads to a crash. (I have tested this running from XCode, but not directly from a rebooted iPad. I don't know for sure the instability persists if not running in XCode using DEBUG mode.)

I've also tried the method in this post. This works, too, but does not return the system to its original state, and again, only works once. (If you try this at home, include Apple's <unisys.h> instead of <io.h>, and leave the _ off of calls like _dup and _dup2.)

I really don't want to have to go through the code and replace all uses of printf, etc to use an explicit file. In addition to being time consuming, error prone, and ugly, the code is open source. I don't expect the original authors would appreciate my changes, and I don't really want to have to reintegrate the changes each time the original project is updated.

Thoughts?

Community
  • 1
  • 1
Mike
  • 3,084
  • 1
  • 25
  • 44
  • The method you linked to using `dup` is a standard way to achieve this, and the code given in that answer does revert file descriptor 1 afterwards - which isn't always required. Also these changes are on a per process basis down the tree (inherited by child processes but do not affect parents). Given that it is unclear what you are meaning with "does not return the system to its original state, and again, only works once". Can you give more detail in the question of what you're trying to do and what you are seeing? That might help someone give you an answer. – CRD Feb 18 '15 at 21:37
  • Running under iOS using XCode, returning standard out to its original setting does not result in text printed with printf() going to the XCode console. The system is also unstable; I am seeing intermittent crashes of the program after resetting stdout. These are definitely not predictable, but they do go away if I do not redirect stdout. – Mike Feb 18 '15 at 23:27

0 Answers0