0

I was trying to redirect the output from an arduino ( USB ) to some file at the computer using the next code:

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

int main()
{

    pid_t pid;
    pid = fork();
    if (pid == 0) {
    execl("/bin/cat","cat /dev/cu.usbmodem1421 - 9600 >> data.txt",NULL);

    }   
    printf("Cuando desee terminar la recolección de datos presione cualquier tecla: ");

    getchar();
    kill(pid, SIGKILL);
    return 0;
}

Using ps to verify if everything is fine, i can see the process running behind my main program. After stoping the program the data file has nothing on it. I tried to use system() which is a little bit nasty because i need to kill the program manually using OSX terminal. I think maybe the syntaxis is wrong and all i need is to add another parameter but nothing seems to work.

mrmurmanks
  • 33
  • 12

2 Answers2

0

Seems like you're doing a fork/execl to do something you could do using simple file I/O.

That being said... execl syntax is, you pass each parameter separately, followed by a null pointer. So, something like this (taking your command literally...):

execl("/bin/cat", "/dev/cu.usbmodem1421", "-", "9600", ">>", "data.txt", (char *) NULL);
John
  • 186
  • 5
  • `>> "data.txt"` is not a parameter, it is a shell operation that cannot be used here. –  Feb 27 '14 at 19:55
  • Fair enough. Like I said, I was taking his command literally to give him an example of the function. You provide another reason to not try to do it this way, and rather to use file I/O to accomplish the task. – John Feb 27 '14 at 19:56
0

As written, your code executes /bin/cat with the name (argv[0]) of:

cat /dev/cu.usbmodem1421 - 9600 >> data.txt

and no other arguments, so it reads from its standard input and writes to its standard output and sits around until it detects EOF on its standard input (or you kill it).

The simplest option is to use system() to run the command.

Failing that, you will need to split up the string into separate arguments, and handle the I/O redirection in the child. Note that the code would read from 3 files:

/dev/cu.usbmodem1421
-
9600

The second would be interpreted as standard input again. If the 9600 is meant to be a modem speed or something, cat is the wrong command.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278