开发者

Use output of unfinished process in a C program

开发者 https://www.devze.com 2023-02-10 11:14 出处:网络
I am using tcpstat in a linux environment. I want to capture its output in a C program even though it has not finished. I tried using the popen() function, but it can only process the output after the

I am using tcpstat in a linux environment. I want to capture its output in a C program even though it has not finished. I tried using the popen() function, but it can only process the output after the program has finished. I want to process the output of tcpstat on the fly as and when it prints it on standard output. How do i do so?

For example,

$ tcpstat -i wlan0 1
Time:1297790227 n=2 avg=102.50  stddev=42.50    bps=1640.00
Time:1297790228 n=11    avg=86.36   stddev=19.05    bps=7600.00
Time:1297790229 n=32    avg=607.97  stddev=635.89   bps=155640.00
Time:1297790230 n=13    avg=582.92  stddev=585.55   bps=60624.00

The above output keeps going on till infinity. S开发者_如何学Goo I want to process the output in a C program as and when tcpstat outputs something onto stdout.

Thanks and Regards,

Hrishikesh Murali


Run tcpstat -i wlan0 -a 1 | your_program and read from the standard input in your program. This way the shell will take care of the piping.

The popen library function and the pipe system call can be used to achieve the same result at a lower level. You may want to take a look at named pipes too - they appear like files in userspace and can be manipulated in the same way.


Run tcpstat with the -F option, this will cause it to flush its output on every interval. (instead of using the default block buffering for stdout)

In addition, you may want to explicitly disable the buffering on your popen FILE handle using setbuf, eg.

setbuf(popen_fd, NULL);

Alternately, you can set it to be line buffered, using setlinebuf

setlinebuf(popen_fd);
0

精彩评论

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

关注公众号