Executing terminal command in objective C with Dynamic path - objective-c

May be my question is a repeated question but I searched a lot of it on the internet and can't find the appropriate and helpful solution.
I want to run the terminal command 'mv' for moving a folder from the root '~/' to another folder but its not working command is running properly using the NSTask library but I think the path is not correct my xcode compiler doest find '~/Desktop',
Sample Code:
NSTask *task = [[NSTask alloc]init];
[task setLaunchPath:#"/bin/mv"];
[task setArguments:#[ #"~/Desktop/Script",#"~/Desktop/Script2"]];
[task launch];
and it gives error:
mv: rename ~/Desktop/Script to ~/Desktop/Script2: No such file or directory
I think the '~/' is not working and xcode cant find the file,
please help
Thanks in advance

The ~ directory is not expanded as you have suspected.
You should use NSHomeDirectory() and concatenate.

Related

Objective C - NSTask support

I am programming an advanced Executable (binary) Analyser Application that can do many operations on Mach-O binaries. One of these functions is a simple launch operation with can simply execute the executable and log its output.
I recently found out the when terminal launches executable files, it detects when the executable runs its own NSTask inside its code.
eg.
Terminal is executing my application and is also showing (in the red circle) that my application is currently running an NSTask of the "file" command:
What I want to figure out is how I can make my app do this to other executable files. I want my app to launch an Executable and when the executable runs a shell script (NSTask), My app will detect it and log it.
eg.
An Executable has the following code:
int main(int argc, const char * argv[]) {
NSTask *task = [NSTask new];
task.launchPath = #"/usr/bin/file";
task.arguments = #[#"--mime", #"--brief", #"/path/to/file"];
task.standardOutput = [NSPipe new];
[task launch];
return 0;
}
When I execute this in Terminal, once the line
[task launch];
is executed, Terminal will display the sub process name in the titlebar:
I Want my app to execute an Executable just like terminal and when an executable runs its own NSTask, I want my app to detect that and log it.
So when my app runs this executable. I want my app to detect when the "file" task is executed in the executable.
I Hope this isn't to difficult to Understand. I also have a feeling I will have to dig deeper than NSTask to include this process.
Thanks.

Different $PATH from Console and Cocoa?

OK, I must be missing something very simple but here's what:
If I echo $PATH in the terminal, I'm getting /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/drkameleon which is correct
Now if I run an NSTask and try executing a simple bash script (/usr/bin/env bash myscript.sh) to echo $PATH, it prints /Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin
(I've even tried with getenv, or print the entire [[NSProcessInfo processInfo] environment] dictionary, but the PATH variable is simply... wrong)
What's going on? How can I have access to the real $PATH as seen in the terminal?
When executing a command via NSTask, not your bash, zshell or whatever kind of shell you are using, is started. Hence the PATH (and other environment variables) are different from your environment variables when echoing them in the terminal.
Reason: NSTask uses fork() and exec() for command execution.
IMHO, there are two possible solutions for the problem.
1. You could set the wanted PATH via the setEnvironment:method of NSTask
Here is some untested example code, which should do the trick:
NSTask *task = //Configure your task
NSDictionary* env = [task environment];
NSString* currentPATH = env["PATH"];
NSString* yourPathExtension = #"/your/path";
env["PATH"] = (currentPATH != nil) ? [yourPath stringByAppendingFormat:#":%#", currentPATH] : yourPathExtension;
[task setEnvironment:env];
This adds :<old-PATH> after the current PATH from NSTask.
2. You could start /bin/bash within NSTask
task setLaunchPath:#"/bin/bash"];
NSArray *args = [NSArray arrayWithObjects:#"-l",
#"-c",
#"<your command here>",
nil];
[task setArguments: args];
This task will start /bin/bash with the PATH configured via ~/.bashrc etc. and execute the command within the bash.
Pro: Your command has all the usual environment variables of your bash
Con: You rely on the users PATH variable which can be quite different from yours which may lead to unexpected behavior.
Which solution is the best one for you depends on your use case. In your provided example, both approaches should work fine.
In general, according to the NSTask and NSProcessInfo documentation, the environment variables are equal to the variables of the process from which the application has been started. Hence you might solve your problem when starting your application from the bash.

How to open a jar file in a Cocoa App

I am trying to execute a jar in my Cocoa app. My research tells me I should use NSTask. However, I am only able to get system() to work. E.g.:
// This works
system("cd /path/to ; /usr/bin/java -jar file.jar");
But this doesn't work:
// This does not work
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:#"/usr/bin/java"];
[task setArguments:[NSArray arrayWithObjects: #"-jar", #"/path/to/test.jar", nil] ];
[task launch];
I get a class not found Java exception when I run my app because it cannot find its dependencies.
There is no general error in your code, I tried it out myself.
I assume that you have defined a CLASSPATH environment variable in your .profile, .bashrc or whatever, that is required to execute the Java file.
system() uses the shell to execute your command, and therefore the CLASSPATH is inherited by the java command.
NSTask on the other hand does not use the shell, so java would not know about the CLASSPATH from your profile.
The solution would be to add #"-cp", #"<your class path>" to the arguments.
UPDATE
As it turned out in the discussion, the problem in this case was not the class path, but the current working directory. Adding
[task setCurrentDirectoryPath:#"/path/to"]
solved the issue.

Problems with NsTask to execute terminal command

Normally in the terminal I would execute this command to communicate with a serial USB device.
echo -e '\xFF\x01\x01' > /dev/cu.usbserial-A8003YzT
I'm trying to do this from within a cocoa app using NStask, but I'm getting no love for some reason.
Heres my code:
- (IBAction) doCommand:(id)sender{
{
NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath:#"/bin/echo"];
[task setArguments:
[NSArray arrayWithObjects:#"-e '\\xFF\\x01\\x01' > /dev/cu.usbserial-A8003YzT", nil]];
[task launch];
[task release];
}}
I know the code is essentially working, as I've executed other terminal commands with the same script.....not sure why I can't get the echo to fire....perhaps I'm missing somthing simple?
Thanks for any help
You're trying to send '\xFF\x01\x01' > /dev/cu.usbserial-A8003YzT as the first argument to echo, but that's not what happens when you run that command from a shell prompt. Only the first, quoted part is sent as an argument to echo. Bash interprets the > itself, captures the output from the echo command, and redirects it to the indicated file - in this case, a file that represents a usb device.
If you want to run an NSTask that will interpret a shell command with redirects, pipes, and such, you'll need to use /bin/sh as the launch path, and -c, your shell command as arguments.
Alternatively, you could skip the NSTask altogether, and simply open an NSFileHandle to the device file, then send the three-byte sequence you want to send it. Echo is handy for interactive debugging stuff like this in a terminal, but launching an external task in your app, just to write three bytes to a file, is pretty drastic overkill... :-)

NSTask sending an argument through /bin/sh or /bin/bash problem Cocoa Objective-C

Basically I've passed a script in the terminal through /bin/bash "[path]" or /bin/sh "[path]", and I've passed commands in a terminal through /bin/bash -c "[command]" or /bin/sh -c "[command]". Both ways work properly. But in my Cocoa App, when I try to do the exact same thing with NSTask (using /bin/bash or /bin/sh), the app seems to never respond. It is as if the program is stuck inside of bash or sh. I've tried to do this with and without waitUntilExit, and I've also tried to use terminate. Still no luck. Has anyone else had this issue or have a clue as to why this is happening?
Thanks!
P.S. I'm not on my work computer right now, but, if needed, I can provide code later.
Ok. So I found the solution for anyone else that might need it. Basically, there is a problem is the standardInput. The problem only shows up in the Xcode console and is not an error/bug with your app. The fix is to add the following line (basically set the standardInput to something random):
[task setStandardInput: [NSPipe pipe]];
In the solution above, task is the variable name of the NSTask being used.
Also see:
http://www.cocoadev.com/index.pl?HowToPipeCommandsWithNSTask
[proc setLaunchPath:#"/bin/bash"];
[proc setArguments:[NSArray arrayWithObjects: #"-c", #"/usr/sbin/netstat -rn | /usr/bin/grep default", nil]];