1

I try to get lost packets number (from ping command on raspberry) which I use for sim switching on router. I tried to do that with code at the bottom (reduced to error causing part), but when I try to free (pclose) buffer I get segmentation fault. I've tried valgrind and I got this:

Invalid read of size 4 at 0x490FBE0: fclose@@GLIBC_2.4 (iofclose.c:53) Address 0x382e3820 is not stack'd, malloc'd or (recently) free'd Process terminating with default action of signal 11 (SIGSEGV) Access not within mapped region at address 0x382E3820

I guess I'm missusing fscanf but I don't know how (I get printf result and it's correct - 4).

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "params.h"
#include <pthread.h> 

void *pingOnly(void *vargp){

    FILE *cmd;
    int packetsReceived=0;
    while(1){
        cmd = popen("sudo ping 8.8.8.8 -c 4 -q","r");
        fscanf(cmd, "%[^,], %d", &packetsReceived);
        printf("%d\n", packetsReceived);
        pclose(cmd);        
        if(packetsReceived<3){
            //testSpeed();
        }
        sleep(300);
    }
    return NULL;    
}

int main( int argc, char *argv[] )
{ 
    pthread_t thread_id[3]; 
    pthread_create(&thread_id[2], NULL, pingOnly, NULL);
    pthread_join(thread_id[2], NULL);
    return 0;
}
Employed Russian
  • 199,314
  • 34
  • 295
  • 362
Bartosz
  • 13
  • 2

1 Answers1

0

The problem is this line

fscanf(cmd, "%[^,], %d", &packetsReceived);

which tries to read a string into int packetsReceived and runs off into undefined behavior, smashing the stack. You probably meant to do

fscanf(cmd, "%*[^,], %d", &packetsReceived);
Chris Dodd
  • 119,907
  • 13
  • 134
  • 226