views:

193

answers:

3

Hey guys,

Do you guys know how to run terminal commands from you GUI application? I need the coding for my app. For example, if I type "netstat" in terminal it will give me all the ports. I want to this from my xcode app. Is that possible? BTW it's not just the "netstat" command it could be "sudo.... "

Thanks, Kevin

+1  A: 

If you're willing to drop down to C, you could just use the system() function. Of course, this will print the results of the command. If you want to store the results of the command, you'll probably want to use a pipe.

Chris Lutz
+1  A: 

Have a look at NSTask for a more Cocoa-like way of doing this.

JimG
+3  A: 

Here is some code I just cut out of one on my apps that uses NSTask.

NSTask* task = [[[NSTask alloc] init] autorelease];
[task setLaunchPath: @"/usr/bin/java"];

NSArray* args = [NSArray arrayWithObjects: @"-jar", jar, @"--cue", inp, @"--dir", dir, mp3, nil];
[task setArguments: args];

taskOutputFile = [[self createTmpFile] retain];
NSFileHandle* taskOutput = [NSFileHandle fileHandleForWritingAtPath:taskOutputFile];

[task setStandardOutput: taskOutput];
[task launch];

This launches an app (java) and records the output in a temp file

FigBug