Rerouting stdin and stdout from C

前端 未结 8 1397
终归单人心
终归单人心 2020-11-22 12:15

I want to reopen the stdin and stdout (and perhaps stderr while I\'m at it) filehandles, so that future calls to printf()

8条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 12:56

    The os function dup2() should provide what you need (if not references to exactly what you need).

    More specifically, you can dup2() the stdin file descriptor to another file descriptor, do other stuff with stdin, and then copy it back when you want.

    The dup() function duplicates an open file descriptor. Specifically, it provides an alternate interface to the service provided by the fcntl() function using the F_DUPFD constant command value, with 0 for its third argument. The duplicated file descriptor shares any locks with the original.

    On success, dup() returns a new file descriptor that has the following in common with the original:

    • Same open file (or pipe)
    • Same file pointer (both file descriptors share one file pointer)
    • Same access mode (read, write, or read/write)

提交回复
热议问题