Cocoa Objective-C shell script from application?

后端 未结 2 1631
萌比男神i
萌比男神i 2021-02-04 21:58

I have an application that I\'m creating and would like to run a shell scripts from within it. One of the scripts creates a .plist file, and the other does a patch on a binary f

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-04 22:34

    You'll need to use NSTask. NSTask is a system for running any Terminal command. Here's how you could use it to execute a shell script:

    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath:@"/path/to/script/sh"];
    [task setArguments:[NSArray arrayWithObjects:@"yourScript.sh", nil]];
    [task setStandardOutput:[NSPipe pipe]];
    [task setStandardInput:[NSPipe pipe]];
    
    [task launch];
    [task release];
    

    That would run the command /path/to/script/sh yourScript.sh. If you need any arguments for your script, you can add them to the array of arguments. The standard output will redirect all output to a pipe object, which you can hook into if you want to output to a file. The reason we need to use another NSPipe for input is to make NSLog work right instead of logging to the script.

    If you want more info on how NSTask works, see this answer.

提交回复
热议问题