Domanda

I'm at a point in a project where I need to call system commands. I originally started looking at NSTask (as that seems to be the most popular approach) but recently i just came across the system command. It looks like a far easier setup that NSTask. I've seen some questions/answers that say NSTask is the better approach, but I don't see

  1. What are the advantages/disadvantages between the two
  2. In what cases would one more likely to be used than the other

Any help/links/thoughts/ideas? (and yes.. i did a google search)

È stato utile?

Soluzione

NSTask:

  • Can run his task in the background. Allows you to send interrupts and kills to the underlying process, and allows you to suspend or resume the underlying process without setting up threads yourself. Can also run synchronously if that's what you want.
  • Let's you work back and forth with Cocoa classes, like NSStrings without having to do a buncha conversions.
  • Let's you set I/O streams for the underlying process that differ from the caller's.
  • Better supported across all Apple platforms (like iOS) than system(3) -- I don't think system even works on iOS.
  • Requires Cocoa and Objective-C.
  • Doesn't interpret shell arguments or do path expansions of arguments.

system(3):

  • Better supported across all Unix-like platforms.
  • Can run a task with a one-liner.
  • Only requires C.
  • Runs in a shell and will interpret working directory and arguments like /bin/sh would.

For a Cocoa app I always use NSTask; I only use system if I'm doing something that must be C-only or I know will have to run under non-Mac environments. As it is, system is pretty brittle and the more robust solution is doing a fork-exec, because it allows you more control over streams and concurrent operation.

Altri suggerimenti

There are some differences. For some of them it is probably har to say in general, whether it is an advantage or not.

  • system() starts a shell. NSTask don't.
  • system() blocks. NSTask run asynchronously.
  • system() only takes args. NSTask works with pipes.
  • system() has only an integer exit code. NSTask works with pipes. (Yes, mentioned again. This is for output.)
  • system() takes a complete command line. To NSTask args can be passed in an array.
  • system() runs on the current directory. To NSTask you can pass a working directory.

This are some differences out of my mind without rechecking the documentation. It is an overview.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top