对于输出重定向大家应该都比较了解了,一般都是指把输出重定向到一个文件中,而对于输入重定向一般就不是很常用了。暂时的一个应用就是实现程序的脚本控制,比如你用脚本启动另一个程序,然后又需要给这个启动的程序发送命令,这时就需要采用输入重定向了,这对于一些服务类型的程序还是很有用的。要实现真正意义的输入重定向还是比较麻烦的,需要用到管道。
下面用一个简单的示例来实现程序的输入,输出重定向。
//file_name:shi_li.cpp
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <signal.h>
#define MAX_LINE 80
#define PIPE_STDIN 0
#define PIPE_STDOUT 1
int main(){
int child_pid;
char outPath[30];
strcpy(outPath,"./out.file");
int pfds[2];
if (pipe(pfds)== 0){
child_pid=fork();
//in child process the return pid==0
if ( child_pid == 0 ) {
//input file,may be used later.
//char inPath[30];
//strcpy(inPath,"./in.file");
//int inFd = open(inPath,O_RDWR|O_CREAT,S_IRUSR|S_IWUSR);
int outFd = open(outPath,O_WRONLY|O_APPEND|O_CREAT,S_IRUSR);
close(0);
dup2( pfds[PIPE_STDIN], 0);
dup2(outFd,1);
close(pfds[PIPE_STDOUT]);
execl("./getstring","getstring",NULL);
printf("start getstring: error!!!");
exit(1);
}
else {
close(pfds[PIPE_STDIN]);
char msg[MAX_LINE];
int b=1;
for(b=1;b<6;b++){
sleep(1);
sprintf(msg,"2+%d\n",b);
write( pfds[PIPE_STDOUT], msg, strlen(msg) );
}
close(pfds[PIPE_STDOUT]);
sleep(2);
printf("all done.\n");
}
}
return 0;
}
接下来是一个很简单的程序输入:
//file_name: getstring.cpp
#include <unistd.h>
#include <iostream>
using namespace std;
int main(){
string tmp;
while(cin >> tmp,!cin.eof()){
if(cin.bad()){
cerr<<"io stream error"<<endl;
exit(1);
}
if(cin.fail()){
cerr<<"io stream error"<<endl;
cin.clear(istream::failbit);
continue;
}
//ok to process
cout<<"all done well:"<<tmp<<endl;
}
}
编译并运行:
#g++ -o getstring getstring.cpp #g++ -o shi_li shi_li.cpp #./shi_li
上述代码包括两个小程序,getstring简单的接收输入的字符串并在终端上回显。shi_li程序负责启动getstring并把输入重定向到管道,输出重定向到out.file文件。执行代码后我们可以查看out.file文件来获得程序执行的结果。
上述小程序可以用在脚本时对向子程序发送命令,从而完成程序测试的自动化。上述代码只是个demo,如果想在实际测试中可用还需要根据自己的情况进行些许修改。
参考资料:
[1] http://blog.chinaunix.net/u/19573/showart_1225848.html
[2]http://www.opengroup.org/onlinepubs/009695399/
Recent Comments