Posted By

zingo on 07/09/11


cocoa osx objc system NSTask

Versions (?)

Quickest Way to Shell - Use system() instead of NSTask

 / Published in: Objective C


Cocoa provides NSTask to run subprocesses. It can be used to run shell scripts, but all this manual pipe and file handling is a bit cumbersome. Fortunately, for a simple script, we can use the trusty old system and redirect its result to a file.

  1. // We'll save the result in a temp file
  2. NSString* tempFilePath = [NSString stringWithFormat:@"%@/MyApplicationLastCrash.txt", NSTemporaryDirectory()];
  4. // Run the shell script
  5. NSString* script = [NSString stringWithFormat: @"ls -1t /Users/mini/Library/Logs/CrashReporter/* | grep /MyApplication | head -1 | tr -d '\n' >%@", tempFilePath];
  6. system([script UTF8String]);
  8. // Returns path to last crash report or empty string ( [lastCrash length == 0] )
  9. NSString* lastCrash = [NSString stringWithContentsOfFile:tempFilePath encoding:NSUTF8StringEncoding error:nil];

Report this snippet  

You need to login to post a comment.