Execute terminal commands from a GUI application?

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

Thanks, Kevin

+2


source to share


3 answers


Here is the code I just cut from one application using 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 starts the application (java) and writes the output to the temp file

+3


source


If you want to go down to C, you can just use the function system()

. Of course, this will print the command results. If you want to save the command results, you probably want to use a pipe.



+1


source


Check out NSTask for a more Cocoa-like way of doing this.

+1


source







All Articles