- 论坛徽章:
- 0
|
突发奇想:能不能把系统调用的结果保存到C变量中
我是用管道实现的:
http://www.cnblogs.com/daniel/articles/29328.aspx
该程序用来执行由命令行传递的命令,并动态显示! 不对之处请各位大侠多多指教!!
例如运行如下:
./my_system ping 127.0.0.1 [回车]
PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.078 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.053 ms
64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.052 ms
64 bytes from 127.0.0.1: icmp_seq=4 ttl=64 time=0.051 ms
64 bytes from 127.0.0.1: icmp_seq=5 ttl=64 time=0.052 ms
64 bytes from 127.0.0.1: icmp_seq=6 ttl=64 time=0.051 ms
........
//////////////////////////////////////////////////////////////////////
#include <stdio.h>;
#include <unistd.h>;
#include <string.h>;
static int my_system(const char* pCmd, char* pResult, int size)
{
int fd[2];
int pid;
int count;
int left;
char* p = 0;
int maxlen = size - 1;
memset(pResult, 0, size);//
if(pipe(fd))//
{
printf("pipe error\n" ;
return -1;
}
if( (pid = fork()) == 0 )//
{// chile process
close( 1 );
dup2( fd[1],1 );//
close( fd[1] );
close( fd[0] );
system( pCmd );//
exit( 0 );
}
// parent process
close( fd[1] );
p = pResult;
left = maxlen;
while( ( count = read( fd[0], p, left ) ) )//
{
pResult = p;
p += count;
left -= count;
if( left == 0 )
break;
printf( "%s\n", pResult );
}
close( fd[0] );
return 0;
}
int main( int argc, char *argv[] )
{
int i = 1;
char spac[] = " ";
char pCmd[1025];
if( argc < 2 )
{
printf( "Syntax error...\n" );
return 255;
}
memset(pCmd, 0, strlen(pCmd) );//
for( ; i < argc; i++ )
{
strcat( pCmd, argv );//
strcat( pCmd, spac );//
}
char result[1024];
my_system( pCmd, result, 1024 );//
printf( "\n%s\n", result );
return 0;
}
//////////////////////////////////////////////////////////// |
|