Run shell script from cocoa (obj.c) with answer

I have something like:

- (NSString *)unixSinglePathCommandWithReturn:(NSString *)command { NSPipe *newPipe = [NSPipe pipe]; NSFileHandle *readHandle = [newPipe fileHandleForReading]; NSTask *unixTask = [[NSTask alloc] init]; [unixTask setStandardOutput:newPipe]; [unixTask setLaunchPath:@"/bin/sh"]; [unixTask setArguments:[NSArray arrayWithObjects:@"-c", command , nil]]; [unixTask launch]; [unixTask waitUntilExit]; NSString *output = [[NSString alloc] initWithData:[readHandle readDataToEndOfFile] encoding:NSUTF8StringEncoding]; return output; } 

But it does not work as expected. I call it when I press the button. If I delete the line with 'waitUntilExit', it works as expected, but only once. When he is there, he does not work. I also tried some basic commands, such as "ls" ping -c1 google.com "and the like, but I can't get it to work somehow. If you have a different approach for running shell scripts in cocoa to get an answer, please let me now.Thank you all :)

+4
source share
4 answers

Hey Cookock. Theres a CocoaDev comment about NSLog() issues when starting NSTask. The fix is ​​to set up the handset for stdin before starting the task:

 [task setStandardInput:[NSPipe pipe]]; 

If you rely on NSLog() only to verify that the task has completed, this may solve your problem. Alternatively, you can try to present output in a graphical interface instead of NSLog() .

+5
source

The problem is that you are not freeing the output buffers of the task. You cannot simply run the task and waitUntilDone if the task also did not produce an extremely small amount of data.

waitUntilDone will obviously not work with a task that never waitUntilDone .

For a task that emits any amount of output, you need to configure it so that the output is read as it is created. Typically, you use readInBackgroundAndNotify or an option in it.

In any case, the top of the class description for NSTask has both links to a conceptual guide, and a number of examples that cover this.

+2
source

And, there is a very important line in the documents that you seem to have missed, one of those annoyances that looks like NextStep: "An NSTask object can be run only once. Subsequent attempts to start the task cause an error."

So, summarize the wait and add [unixTask release] before returning. When you want to run it again, redo the task.

NSTimer is as follows.

0
source

For different approaches to running shell scripts in Cocoa, see AMShellWrapper, PseudoTTY.app, or OpenFileKiller!

http://www.cocoadev.com/index.pl?NSTask

0
source

Source: https://habr.com/ru/post/1335000/


All Articles