linux下popen函数用法代码
// linux下popen函数用法代码:zread.c,摘自gzip例子
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Trivial example of reading a gzip'ed file or gzip'ed standard input
* using stdio functions fread(), getc(), etc... fseek() is not supported.
* Modify according to your needs. You can easily construct the symmetric
* zwrite program.
*
* Usage: zread [file[.gz]]
* This programs assumes that gzip is somewhere in your path.
*/
int main(argc, argv)
int argc;
char **argv;
{
FILE *infile;
char cmd[256];
char buf[BUFSIZ];
int n;
if (argc < 1 || argc > 2) {
fprintf(stderr, "usage: %s [file[.gz]]\n", argv[0]);
exit(EXIT_FAILURE);
}
strcpy(cmd, "gzip -dc "); /* use "gzip -c" for zwrite */
if (argc == 2) {
strncat(cmd, argv[1], sizeof(cmd)-strlen(cmd));
}
infile = popen(cmd, "r"); /* use "w" for zwrite */
if (infile == NULL) {
fprintf(stderr, "%s: popen('%s', 'r') failed\n", argv[0], cmd);
exit(EXIT_FAILURE);
}
/* Read one byte using getc: */
n = getc(infile);
if (n == EOF) {
pclose(infile);
exit(EXIT_SUCCESS);
}
putchar(n);
/* Read the rest using fread: */
for (;;) {
n = fread(buf, 1, BUFSIZ, infile);
if (n <= 0) break;
fwrite(buf, 1, n, stdout);
}
if (pclose(infile) != 0) {
fprintf(stderr, "%s: pclose failed\n", argv[0]);
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
return 0; /* just to make compiler happy */
}
zread abc.tar.gz
会输出 abc.tar.gz文件的内容
相当于执行: gzip -dc abc.tar.gz
abc.tar.gz 的由来,存在一个文本文件 hello.c
tar zcvf abc.tar.gz hello.c
例子2
python代码 ,看怎么转换为linux c 代码
# -*- coding: utf8 -*-
import sys
import time
import threading
from pywebsocketserver.server import SocketServer
from pywebsocketserver.baseio import BaseIO
import subprocess
def tcpdump():
global g_output_log
popen=subprocess.Popen([‘bash’,‘-c’,“/usr/sbin/tcpdump -i eth0 -v”],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
pid=popen.pid
print(‘Popen.pid:’+str(pid))
while True:
line=popen.stdout.readline().strip()
#line =popen.communicate()
print “output:%s” %(line)
g_output_log.append(line)
if subprocess.Popen.poll(popen) is not None:
break
print(‘DONE’)
class MyIO(BaseIO):
def onData(self,uid,text):
self.sendData(uid,“received the message:%s”%(text,))
def onConnect(self,uid):
global g_uid
g_uid=uid
while True:
#self.sendData(uid,”testing…”)
if len(g_output_log) >0:
log = g_output_log.pop()
self.sendData(uid,log)
else:
time.sleep(.01)
try:
g_output_log=[]
g_uid=None
tcpdump = threading.Thread(name=‘tcpdump’, target=tcpdump)
tcpdump.start()
port = sys.argv[1]
except:
port = 88
port = int(port)
myIo = MyIO()
SocketServer(port,myIo).run()
备注
FILE *tcpdump = popen(“tcpdump -s0 -w - 2>/dev/null”, “r”);
redirect stderr to /dev/null:
FILE *tcpdump = popen(“tcpdump -s0 -w - 2>/dev/null”, “r”);
2>&1 means to redirect stderr to stdout, 2>file means to redirect stderr to file (and redirecting to /dev/null essentially ignores the output)