Re: talking to shell from cocoa/obj-c
Re: talking to shell from cocoa/obj-c
- Subject: Re: talking to shell from cocoa/obj-c
- From: "Clark S. Cox III" <email@hidden>
- Date: Thu, 6 Dec 2001 18:43:37 -0500
On Thursday, December 6, 2001, at 12:58 , Matt Neuburg wrote:
From within a Cocoa / Objective-C program, how do I speak to the shell in
such a way that the response, which would normally go to STDOUT, comes
back to me? As a simple example, how can I say "date" (the Unix command)
in such a way as to learn the date?
I see how to do this sort of thing with an NSTask by using a file on disk
as an intermediary, but I want the Unix command's STDOUT to pipe directly
back to me somehow. I tried to do this with an NSPipe but failed.
You're on the right track. Try something along these lines:
{
NSTask *task = [ [ NSTask alloc ] init ];
NSPipe *stdoutPipe = [ NSPipe pipe ];
NSData *outputData;
[ task setLaunchPath: @"date" ];
[ task setStandardOutput: stdoutPipe ];
[ task launch ];
[ task waitUntilExit ];
//Check [ task terminationStatus ] for commands that might fail
outputData = [ [ stdoutPipe fileHandleForReading ]
readDataToEndOfFile ];
//Do whatever you want with outputData here
[ task release ];
}
--
Clark S. Cox, III
email@hidden
http://www.whereismyhead.com/clark/