How to get the log from system();?

前端 未结 1 441
你的背包
你的背包 2021-01-24 02:41

is there a way to get the log from system(); so like when I do system(\"open com.apple.nike\"); I should get Couldn\'t open application: com.apple.nike. Reaso

相关标签:
1条回答
  • 2021-01-24 03:06

    I know this isn't exactly what you asked, but perhaps there's a better way.

    If you want to run a command (like open com.apple.nike), I think using NSTask is actually the best way to do that programmatically. NSTask will allow you to run commands just like system(), but has good support for handling the standard output from those commands, without having to do file I/O on the system log file.

    For example, here's an example of using NSTask to list directory contents (ls -altr), and capture the output in a NSString:

    - (void) listDir {
       NSTask *task = [[NSTask alloc] init];
       [task setLaunchPath: @"/bin/ls"];
       [task setArguments: [[NSArray alloc] initWithObjects: @"-altr", nil]];
    
       NSPipe *pipe= [NSPipe pipe];
       [task setStandardOutput: pipe];
    
       NSFileHandle *file = [pipe fileHandleForReading];
    
       [task launch];
    
       NSData *data = [file readDataToEndOfFile];
    
       NSString *output = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
       NSLog(@"result: %@", output);
    }
    

    This will keep the output from your open command separate from any other stuff in the system log file.

    NSTask is a private API on iOS, but as is the case with many APIs that exist on OS X, they actually are available on iOS (just don't assume Apple allows them in the App Store!).

    To use it, you'll need to download the NSTask.h header, and include it in your project.

    Here's an old version, but I bet it still probably works.

    0 讨论(0)
提交回复
热议问题