Objective-C 中的 Unix 系统调用

发布于 2024-08-14 21:14:48 字数 223 浏览 2 评论 0原文

Objective-C 可以进行系统调用吗?

我有以下代码:

if (!system("ls -l")) {
    NSLog(@"Successfully executed"); 
} else {
      NSLog(@"Error while executing the command"); 
}

如何获取输出?

谢谢

Is it possible to make system call in Objective-C?

I have the following code:

if (!system("ls -l")) {
    NSLog(@"Successfully executed"); 
} else {
      NSLog(@"Error while executing the command"); 
}

How to get the output?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

メ斷腸人バ 2024-08-21 21:14:48

这是使用 -[NSFileManagercontentsOfDirectoryAtPath:error:] 而不是包装内置 shell 函数并解析输出。对于需要输出的通用命令 - 并且 Cocoa 中没有“免费”的等效功能(只需要时间来学习可用的 API) - NSTask 通常是比 system() 更好的替代方案。

This is a perfect candidate for using -[NSFileManager contentsOfDirectoryAtPath:error:] instead of wrapping a built-in shell function and parsing the output. For general-purpose commands where you need the output — and where there is no equivalent functionality "for free" in Cocoa (it just takes time to learn the available APIs) — NSTask is generally a far better alternative than system().

半岛未凉 2024-08-21 21:14:48

您应该使用 NSTask 。如果您只需要 ls 的结果,Cocoa 中有更合适的文件系统包装器。

You should use NSTask. If you just need the results of ls, there are more appropriate filesystem wrappers in Cocoa.

总以为 2024-08-21 21:14:48

如果您喜欢以 C 方式执行此操作,可以使用 popen。这也可以用于读取输出。但关于使用 Objective-C 解决方案的答案可能是更好的答案。

If you like to do it the C way you can use popen. This can be used to read the output also. But the answers about using Objective-C solutions are probably the better ones.

萌︼了一个春 2024-08-21 21:14:48

Objective-C 不会阻止程序调用 system() 或其任何等效项。

CocoaTouch 确实如此。

Objective-C does not prevent a program to invoque system() or any of its equivalents.

CocoaTouch does.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文