Execing Processes in Objective-C
Our example demonstrates how to replace the current process with another one in Objective-C. This is similar to the classic exec function in Unix-like operating systems.
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
// For our example we'll exec 'ls'. We need the full path to the binary.
NSString *binary = @"/bin/ls";
// We'll give 'ls' a few common arguments. Note that the first argument should
// be the program name.
NSArray *args = @[@"ls", @"-a", @"-l", @"-h"];
// We also need to provide the current environment.
NSDictionary *env = [[NSProcessInfo processInfo] environment];
// Create an NSTask to run the new process
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:binary];
[task setArguments:args];
[task setEnvironment:env];
// Launch the new process, replacing the current one
[task launch];
[task waitUntilExit];
}
return 0;
}In this Objective-C version, we use NSTask to create and launch a new process. While it doesn’t directly replace the current process like syscall.Exec in the original example, it achieves a similar result by launching a new process and waiting for it to exit.
When we run our program, it will execute the ls command with the specified arguments:
$ gcc -framework Foundation main.m -o execing-processes
$ ./execing-processes
total 32
drwxr-xr-x 4 user staff 128B Jul 10 15:30 .
drwxr-xr-x 10 user staff 320B Jul 10 15:29 ..
-rwxr-xr-x 1 user staff 17K Jul 10 15:30 execing-processes
-rw-r--r-- 1 user staff 554B Jul 10 15:30 main.mNote that Objective-C and the iOS/macOS environment don’t offer a direct equivalent to Unix’s fork function. However, for most use cases, creating new processes or using concurrent programming features like Grand Central Dispatch (GCD) or NSOperation can cover similar functionality.
Comments powered by Disqus