1

I have this example of using NSTask in Objective-C

NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/bin/bash"];
[task setArguments:@[ @"-c", @"cp /Directory/file /users/user_name/Desktop" ]];
[task launch];

I want to know if the [task setArguments:] returns a state of success or failure for executing that command, and save the state to check afterwards. How can I get that result?

jscs
  • 63,694
  • 13
  • 151
  • 195
Programmer
  • 103
  • 1
  • 9
  • Why copy files this way instead of using a more direct API like [`NSFileManager`](https://developer.apple.com/documentation/foundation/nsfilemanager)? (It's got [`-copyItemAtPath:toPath:error:`](https://developer.apple.com/documentation/foundation/nsfilemanager/1407903-copyitematpath?language=objc)) – Itai Ferber Jul 28 '17 at 23:01

2 Answers2

1

I want to know if the [task setArguments:] returns a state of success or failure for executing that command, and save the state to check afterwards.

Why do you think setting the arguments of the task, that is not yet launched and running, might return the status of running the command?

How can I get that result?

Read the documentation for NSTask, its method waitUntilExit, and its property terminationStatus.

That said, as @ItaiFerber raises in the comment, hopefully this is just an example and you are not really using NSTask to run cp.

CRD
  • 52,522
  • 5
  • 70
  • 86
0
    NSPipe *pipe = [[NSPipe alloc] init];
    NSFileHandle *file = pipe.fileHandleForReading;
    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath:@"/bin/bash"];
    [task setArguments:@[ @"-c", @"cp /Directory/file /users/user_name/Desktop" ]];
    task.standardOutput = pipe;
    [task launch];
    if(task.isRunning)
        [task waitUntilExit];

    int status = [task terminationStatus];
    if(status == 0){}
Vikram Sinha
  • 581
  • 1
  • 10
  • 25