NsTask执行终端命令的问题
通常,我会在终端中执行此命令来与串行 USB 设备进行通信。
echo -e '\xFF\x01\x01' > /dev/cu.usbserial-A8003YzT
我正在尝试使用 NStask 在可可应用程序中执行此操作,但由于某种原因我没有得到任何支持。
这是我的代码:
- (IBAction) doCommand:(id)sender{
{
NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath:@"/bin/echo"];
[task setArguments:
[NSArray arrayWithObjects:@"-e '\\xFF\\x01\\x01' > /dev/cu.usbserial-A8003YzT", nil]];
[task launch];
[task release];
}}
我知道代码本质上是有效的,因为我已经使用相同的脚本执行了其他终端命令......不知道为什么我无法让回声触发......也许我错过了简单的事吗?
感谢您的帮助
Normally in the terminal I would execute this command to communicate with a serial USB device.
echo -e '\xFF\x01\x01' > /dev/cu.usbserial-A8003YzT
I'm trying to do this from within a cocoa app using NStask, but I'm getting no love for some reason.
Heres my code:
- (IBAction) doCommand:(id)sender{
{
NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath:@"/bin/echo"];
[task setArguments:
[NSArray arrayWithObjects:@"-e '\\xFF\\x01\\x01' > /dev/cu.usbserial-A8003YzT", nil]];
[task launch];
[task release];
}}
I know the code is essentially working, as I've executed other terminal commands with the same script.....not sure why I can't get the echo to fire....perhaps I'm missing somthing simple?
Thanks for any help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在尝试发送
'\xFF\x01\x01' > /dev/cu.usbserial-A8003YzT
作为echo
的第一个参数,但当您从 shell 提示符运行该命令时,情况并非如此。只有第一个引用的部分作为参数发送到 echo。 Bash 解释>
本身,捕获 echo 命令的输出,并将其重定向到指定的文件 - 在本例中,该文件代表 USB 设备。如果您想运行一个
NSTask
来解释带有重定向、管道等的 shell 命令,您需要使用/bin/sh
作为启动路径,和-c
、您的 shell 命令
作为参数。或者,您可以完全跳过
NSTask
,只需打开设备文件的NSFileHandle
,然后发送您想要发送的三字节序列。 Echo 对于在终端中进行交互式调试非常方便,但是在您的应用程序中启动外部任务,只是为了将三个字节写入文件,是相当严重的杀伤力......:-)You're trying to send
'\xFF\x01\x01' > /dev/cu.usbserial-A8003YzT
as the first argument toecho
, but that's not what happens when you run that command from a shell prompt. Only the first, quoted part is sent as an argument to echo. Bash interprets the>
itself, captures the output from the echo command, and redirects it to the indicated file - in this case, a file that represents a usb device.If you want to run an
NSTask
that will interpret a shell command with redirects, pipes, and such, you'll need to use/bin/sh
as the launch path, and-c
,your shell command
as arguments.Alternatively, you could skip the
NSTask
altogether, and simply open anNSFileHandle
to the device file, then send the three-byte sequence you want to send it. Echo is handy for interactive debugging stuff like this in a terminal, but launching an external task in your app, just to write three bytes to a file, is pretty drastic overkill... :-)