title: How to use NSTask run terminal commands in loop in consistent environment?
body: <p>I want to use NSTask to simulate the Terminal to run commands. The codes as follows. It can get input in loop and return the process output.</p>
  
  <pre><code>int main(int argc, const char * argv[])
  {
    @autoreleasepool {      
      while (1) {
          char str[80] = {0};
          scanf("%s", str);
          NSString *cmdstr = [NSString stringWithUTF8String:str];
  
          NSTask *task = [NSTask new];
          [task setLaunchPath:@"/bin/sh"];
          [task setArguments:[NSArray arrayWithObjects:@"-c", cmdstr, nil]];
  
          NSPipe *pipe = [NSPipe pipe];
          [task setStandardOutput:pipe];
  
          [task launch];
  
          NSData *data = [[pipe fileHandleForReading] readDataToEndOfFile];
  
          [task waitUntilExit];
  
          NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
          NSLog(@"%@", string);
  
      }
  }
  </code></pre>
  
  <p>My question is: when a loop is end, the running environment restore to the initialization state. For example, the default running path is <code>/Users/apple</code>, and I run <code>cd /</code> to change the path to <code>/</code>, and then run <code>pwd</code>, it return the <code>/Users/apple</code> rather than the <code>/</code>. </p>
  
  <p>So how can I use <code>NSTask</code> to simulate the Terminal completely ?  </p>