Search code examples
cexecforkos.execl

how to use execl corrrectly?


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.


Solution

  • 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.