Search code examples
iossystemnslog

iPhone SDK: System() questions


I got bored earlier and wondered if you could execute terminal commands on the iOS platform. Surely enough, just like OSX you can. This is really awesome, but how do I output what the terminal outputs to a text area or something similar? It's nothing serious, just a fun project.
I am using system("") to do it.


Solution

  • This, my friend is one of the downsides to using system. I also hope you understand that system is unavailable on a non-jailbroken iDevice, so unless you are installing it as instructed on the #1 answer on iPhone App Minus App Store, then you can't use it.

    Now, moving forward, you have a few options.

    1. Pipe the output of the command to a file, and read that file in your application. Your code should look something like this:

      system("myCommand -f \"/path/to/my/file\" > output.txt")
      
      NSString *results = [NSString stringWithContentsOfFile:@"output.txt" usedEncoding:nil error:nil];
      NSLog(@"%@", results);
      
    2. Create the process with the popen function, and then pipe the output directly into your application:

      NSFileHandle *openProcessRead(const char *command)
      {
          FILE *fPtr = popen(command, "r");
      
          NSFileHandle *fileHandle = [[NSFileHandle alloc] initWithFileDescriptor:fileno(fPtr) closeOnDealloc:YES];
      
          return fileHandle;
      }
      

      You can now use the NSFileHandle docs to do what you need.