c++popenpclose

why same output is returned when popn() is calling again and again


I am trying below example

#include <boost/thread.hpp>
#include <boost/thread/condition.hpp>
#include <iostream>

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

std::string exec(char* cmd, boost::uint16_t *piOutVid, boost::uint16_t *piOutPid) {
    boost::uint16_t uint_pid;
    boost::uint16_t uint_vid = 0x05e0;
    piOutVid = &uint_vid;

    FILE* pipe1 = popen(cmd, "r");
    if (!pipe1) return "ERROR";
    char buffer[128];
    unsigned int value;
    std::string result = "";
    while(!feof(pipe1)) {
        if(fgets(buffer, 128, pipe1) != NULL)

            if(strncpy(buffer, "1300", 4))
            {
                uint_pid = 0x1300;
                std::cout << "value: " << buffer << std::endl;
            }
            else if(strncpy(buffer, "1900", 4))
            {
                uint_pid = 0x1900;
                std::cout << "value: " << buffer << std::endl;
            }
            else if(strncpy(buffer, "0820", 4))
            {
                uint_pid = 0x0820;
                std::cout << "value: " << buffer << std::endl;
            }

            result += buffer;
    }
    pclose(pipe1);
    buffer[127] = '\0';


    return result;
}

int main()
{
    boost::uint16_t *piOutVid;
    boost::uint16_t *piOutPid;
    std::cout << "Boost threading..." << std::endl;
    //boost::thread *nwThread = new boost::thread(boost::bind(class::method, this));
    char *cmd = "lsusb|grep 'Symbol'|cut -d \":\" -f 3|cut -d \" \" -f 1";
    exec(cmd, piOutVid, piOutPid);

}

when run this program first time. it worked correctly but reusing the program is not working properly. First time I test with a device (PID = 1300) then remove it and plug a new device (PID = 0820) and run the program again. But still give the same below output.

Boost threading...
value: 1300

Process returned 0 (0x0)   execution time : 0.059 s
Press ENTER to continue.

pclose() returns 0


Solution

  • Your if statements are based on the result of a strncpy, which always returns the memory address of destination. So by definition, if the copy succeeds it's always going to return a value which evaluates to true. And thus always hit your 0x1300 block.

    Did you mean to use strcmp?