Skip to content
Advertisement

output from popen doesn’t capture the error return

I was trying to capture the output from popen.

The command that I am using is

 timeout 1.5 ping -c 1 1.2.3.4 -w 2 | tail -1  | awk '{print $4}' | cut -d '/' -f 2 2>&1

If you execute the above command in shell, you will get a message Terminated. My objective is to get the message Terminated in a buffer. I used the code below, but it didn’t work.

#include <stdio.h>
#include <string.h>
#include <pthread.h> 
#include <errno.h>

char pingTimeToServer[256];
char *gateway = NULL;
char cmd[256] = {0x0};
char receiver_gateway[256];
char c[1000];

int main() {

    strcpy(pingTimeToServer,"TEST");

    FILE *fp;

    //snprintf(cmd, sizeof(cmd), "timeout 1.5 ping -c 1 %s -w 2 | tail -1 | awk '{print $4}' | cut -d '/' -f 2", "1.2.3.4");
    //snprintf(cmd, sizeof(cmd), "timeout 1.5 2>&1 ping -c 1 %s -w 2 | tail -1  | awk '{print $4}' | cut -d '/' -f 2", "1.2.3.4");
    snprintf(cmd, sizeof(cmd), "timeout 1.5 ping -c 1 %s -w 2 | tail -1  | awk '{print $4}' | cut -d '/' -f 2 2>&1", "1.2.3.4");

    if ((fp = popen(cmd, "r")) == NULL)
    {
        return -1;
    }

    while(fgets(pingTimeToServer, sizeof(pingTimeToServer), fp) != NULL)
    {

        printf(" inside IF .................. n");
        pingTimeToServer[strcspn(pingTimeToServer, "rn")] = '';
    }

    printf("********** pingTimeToServer is %sn",pingTimeToServer);
    pclose(fp);
}

Any ideas why it is not working ? Or if there is a better way to do it in C, that will be helpful as well.

Advertisement

Answer

The message is printed by the shell, and only when it’s run in interactive mode. So you need to run a shell process with -i to get the message.

snprintf(cmd, sizeof(cmd), "bash -i -c 'timeout 1.5 ping -c 1 %s -w 2 | tail -1  | awk '\''{print $4}'\'' | cut -d "/" -f 2' 2>&1", "1.2.3.4");
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement