开发者

How to capture unbuffered output from stdout without modifying the program?

开发者 https://www.devze.com 2022-12-08 01:57 出处:网络
I\'m writing a utility for running programs, and I need to capture unbuffered stdout and stderr from the programs. I need to:

I'm writing a utility for running programs, and I need to capture unbuffered stdout and stderr from the programs. I need to:

  • Capture stdout and stderr to separate files.
  • Output needs to not be buffered (or be line buffered).
  • Without modifying the source of the program being run.

The problem is, when piping output to a file, the stdout stream becomes block buffered rather than line buffered. If the program crashes, the output never gets flushed, and is blank. So I need to capture stdout without buffering (or with line buffering).

I think this can be done with pty's but I'm having difficulty finding any examples that do exactly what I want (most ignore stderr). In fact, I'm not sure I've found any pty examples in C at all; most use a higher-level interface like Python's pty and subprocess modules.

Can anyone help (with code snippets or links)? Any help would be appreciated.

EDIT: I think I've solved it. The following two links were pretty helpful.

  • http://publib.boulder.ibm.com/infocenter/zos/v1r10/index.jsp?topic=/com.ibm.zos.r10.bpxbd00/posixopenpt.htm
  • http://www.gidforums.com/t-3369.html

My code is avail开发者_开发问答able as a repository:

  • https://bitbucket.org/elliottslaughter/pty


see man 7 pty


In particular:

Unix 98 pseudo-terminals

An unused Unix 98 pseudo-terminal master is opened by calling posix_openpt(3). (This function opens the master clone device, /dev/ptmx; see pts(4).) After performing any program-specific initializations, changing the ownership and permissions of the slave device using grantpt(3), and unlocking the slave using unlockpt(3)), the corresponding slave device can be opened by passing the name returned by ptsname(3) in a call to open(2).

And now that you know the names of the library functions such a code will need to call, you can do two useful things:

  • Look up their man pages
  • Google for example code. Since you know what keywords to use with the search engine I suspect you will have much more luck hunting down examples.
0

精彩评论

暂无评论...
验证码 换一张
取 消