Вопрос

So I have this function:

void step (NSTextField *input, char move, int position, NSTextField *label) {
  int delta = input.intValue;
  for (int i = 0; i < delta; i++) {
    pclose(popen("echo move > /dev/tty.usbmodem621", "r"));
    position = position +1;
    [NSThread sleepForTimeInterval:t1];
    NSString *printPosition = [NSString stringWithFormat: @"%i", position];
    label.stringValue = printPosition;
  }

}

And in the line:

    pclose(popen("echo move > /dev/tty.usbmodem621", "r"));

Move should be the variable character that I declared at the beginning. But I can't seem to find out how to do that. Could somebody enlighten me?

Also there is an other thing I don't understand. If for example my input is 20 the and i run this script it counts 20 like it supposed to. However when I input a new value it doesn't ad that one up to the 20 that's already there like I hoped it would. Instead it just displays the new value. Any ideas?

Thanks

Это было полезно?

Решение

To generate string with move:

NSString *str = [NSString stringWithFormat:@"echo %c > /dev/tty.usbmodem621", move];

About not adding more characters, it is hard to say with this example. I can see that your position always starts from 0 because it is incoming parameter but not retuned back. Maybe that's the issue?

Другие советы

This is...not how I would do this. You don’t need to open a pipe or do an echo or any of that stuff to write to a device.

Look into doing something like [NSFileHandle fileHandleForWritingAtPath:@"/dev/tty.usbmodem621”], and then writing to it with writeData:

You can get an NSData from an NSString by using -dataUsingEncoding:, probably with the ASCII encoding.

Yikes. Ok - first problem:

Move should be the variable character that I declared at the beginning

No. popen() executes shell commands and there's no way that it can bind to your move variable. What you need to do is compose a shell command with with move character in it. Something like this

char cmd[] = "echo # > /dev/tty.usbmodem621";
cmd[5] = move;
pclose(popen(cmd,"r"));

Which brings me to the second problem: constructing shell commands from external data and then blindly executing them creates an attack vector called "shell injection" which is quite a common way to hack into systems.

As another poster has already indicated, you don't need popen() to do this so if I were you I'd avoid and never compose shell commands unless you really have to.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top