Best way to make executable in Objective-C

I need to be able to run the file using code that works great, but to make sure it succeeds, I must first set the executable bit in the file. I am currently running chmod +x via NSTask, but this seems awkward:

 NSString *script = @"/path/to/script.sh"; // At this point, we have already checked if script exists and has a shebang NSFileManager *fileManager = [NSFileManager defaultManager]; if (![fileManager isExecutableFileAtPath:script]) { NSArray *chmodArguments = [NSArray arrayWithObjects:@"+x", script, nil]; NSTask *chmod = [NSTask launchedTaskWithLaunchPath:@"/bin/chmod" arguments:chmodArguments]; [chmod waitUntilExit]; } 

Any suggestions? I was not lucky to find code examples, and the only other option is NSFileManager setAttributes:ofItemAtPath:error: with the NSFilePosixPermissions attribute. I will do POSIX read and write logic if I need it, but wanted to see if there is a more elegant method there.

+4
source share
2 answers

What is impractical with respect to the NSFileManager method, you must create a dictionary structure that is terribly verbose. POSIX approach:

 #include <sys/types.h> #include <sys/stat.h> const char path[] = "hardcoded/path"; /* Get the current mode. */ struct stat buf; int error = stat(path, &buf); /* check and handle error */ /* Make the file user-executable. */ mode_t mode = buf.st_mode; mode |= S_IXUSR; error = chmod(path, mode); /* check and handle error */ 
+2
source

Use -setAttributes:ofItemAtPath:error: What is not elegant?

Another possibility is to use chmod(2) , the POSIX function.

The solution indicated in your question is expensive - completing a task is equivalent to creating a new process in the operating system, which is definitely more expensive than using NSFileManager or chmod(2) .

+4
source

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


All Articles