Search code examples
cpipefgets

fgets cannot capture output from tty device


I am trying to get the RSSI value from a Option modem installed as ttyHS4 (control) and ttyHS5 (data) on a Linux board. Expected result shows up on console but the fgets just does not capture any console output data.

if ((f=popen("echo -e \"AT+CSQ\r\n\">dev\ttyHS4","r"))==NULL){  
perror("popen");  
exit(1);  
}  

while (fgets(buff,sizeof(buff),f){  
printf(":%s:\n",buff);  
}  

I tested with "echo \"TEST\"" in the popen command and code above was able to print out the ":TEST:" string. With the ttyHS4 output, I only can get a few output on the console but the fgets + fprintf does not get any data to work on.

Please advise where I could have faulted.


Solution

  • You are calling popen() to create a file descriptor that channels to your main program the standard output of this command:

    echo -e ... >/dev/ttyHS4
    

    You do realize that this command sends nothing to that file descriptor, right? popen() opens a shell - normally /bin/sh - which then executes that command. Due to the redirection to /dev/ttyHS4, the echo command does not send its standard output to the same file descriptor as its parent shell, which leads to nothing being written to f - and even if that was not the issue, echo would never read back the modem response to you..

    But why are you even using popen() and echo, instead of just opening /dev/ttyHS4 read/write and using read() and write() on the resulting file descriptor directly?