求助大神,如题~~
我在做一个项目,需要在程序中调用命令行,并返回结果,打印输出。
比如:在程序中调用ping -c 3 www.google.cn
打印出下面的结果:
PING www.google.cn (203.208.45.211): 56 data bytes
64 bytes from 203.208.45.211: icmp_seq=0 ttl=49 time=2.678 ms
64 bytes from 203.208.45.211: icmp_seq=1 ttl=49 time=2.250 ms
64 bytes from 203.208.45.211: icmp_seq=2 ttl=49 time=2.808 ms--- www.google.cn ping statistics ---
3 packets transmitted, 3 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 2.250/2.579/2.808/0.238 ms
这个过程怎么实现???在iPhone中有这样的接口吗?NSTask不能用,Xcode4.3.3。
下面这种方式根本打印不出东西:    NSString *output = [NSString string];
    FILE *pipe = popen([cmd cStringUsingEncoding:NSASCIIStringEncoding], "r+");
    
    if (!pipe)
        return nil;
    
    char buf[1024];
    while (fgets(buf, 1023, pipe))
    {
        output = [output stringByAppendingFormat:@"%s", buf];
    }
    
    pclose(pipe);
    NSLog(@"the output is: %@", output);
请问,还有别的方法吗?

解决方案 »

  1.   

    请搜 SimplePing ,官方Demo
      

  2.   

    SimplePing代码太多了,等下班回去慢慢研究,
    我一直是用真机进行调试的,刚才把下面的代码在模拟器上运行,
    居然可以打印出结果,在真机上为什么就打印不出来任何东西呢?    NSString *output = [NSString string];
        FILE *pipe = popen("ls", "r");
        
        if (!pipe)
            return nil;
        
        char buf[1024];
        while (fgets(buf, 1023, pipe))
        {
            output = [output stringByAppendingFormat:@"%s", buf];
        }
        
        pclose(pipe);
        NSLog(@"the output is: %@", output);
      

  3.   

    模拟器是iOS 5.1, 真机是5.1.1, 跟这个有关系吗?
      

  4.   

    是Root权限的问题,不知道怎么让程序获得Root权限