在Objective-C中使文件可执行的最佳方法是什么?

4

我需要能够通过代码执行一个文件,这个操作很好实现,但是为了确保成功,我必须先设置文件的可执行权限位。目前,我通过NSTask运行chmod +x命令来实现,但这种方法有些笨拙:

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];
}

有什么建议吗?我没有找到任何代码示例,似乎唯一的选择是使用NSFileManager的setAttributes:ofItemAtPath:error:NSFilePosixPermissions属性。如果必要,我将执行POSIX读写逻辑,但想知道是否有更优雅的方法。


小提示:由于字符串字面量是常量,因此在第一行中不需要使用+[NSString stringWithString:] - Jonathan Sterling
是的,这不是我的实际代码(只是为了让脚本代表更清晰),但我已经修改它使其更有意义。 - One Crayon
2个回答

4
请使用-setAttributes:ofItemAtPath:error:方法。这个方法很优雅,没有什么不好的。
另一个可能性是使用chmod(2),它是一个POSIX函数。
你在问题中列出的解决方案很昂贵 - 运行一个任务相当于在操作系统上创建一个新进程,这绝对比使用NSFileManagerchmod(2)更昂贵。

1
“-setAttributes:ofItemAtPath:error:” 绝对是处理这个问题的正确方式。 - Lily Ballard

2
< p > NSFileManager 方法的不够优雅之处在于需要构建一个字典结构,这样非常冗长。采用 POSIX 方法可以解决这个问题:

#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 */

同意,正是字典让我感到不爽。我将尝试使用POSIX方法来提高速度,如果C代码让我感到太糟糕,可能会切换到setAttributes:ofItemAtPath:error:。感谢大家,也感谢Jeremy提供的示例代码! - One Crayon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接