C++ 初始化pid_t变量

C++ 初始化pid_t变量,c++,fork,C++,Fork,Valgrind报告了一个错误: ==5644== Conditional jump or move depends on uninitialised value(s) 这种情况发生在类型为pid\t的变量上 我的代码如下: GmpPipePlayer::GmpPipePlayer( IOBase *pIO, Referee *pBack, PieceColor pc, int size, const DataBoard *pBd, int handicap, const char *cmd_

Valgrind报告了一个错误:

==5644== Conditional jump or move depends on uninitialised value(s)
这种情况发生在类型为
pid\t
的变量上

我的代码如下:

GmpPipePlayer::GmpPipePlayer( IOBase *pIO, Referee *pBack, PieceColor pc, int size, const DataBoard *pBd, int handicap, const char *cmd_line, int bDebug )
    : GmpPlayer(pIO, pBack, pc, size, pBd, handicap, bDebug)
{
    int down[2], up[2];
        pid_t _pid;  //here the var is declared

    pipe(down);   
    pipe(up);


    _pid = fork();

    if (_pid < 0)
        exit(1);


    if (_pid == 0)
    {
        close(down[1]);
        close(up[0]);

        dup2(down[0], 0);
        dup2(up[1], 1);

        execl("/bin/sh", "sh", "-c", cmd_line, NULL);

        _exit(1);
    }

    close(down[0]);
    close(up[1]);
    _down = down[1];
    _up = up[0];

    _reader_thd = new Thread(reader_wrapper, this);
}

GmpPipePlayer::~GmpPipePlayer()
{
    if (_pid > 0)   //valgrind is reporting that the error is here!!
    {
        kill(_pid, SIGTERM);
        _pid = 0;
    }

    if (_up)
    {
        close(_up);
        _up = 0;
    }

    if (_down)
    {
        close(_down);
        _down = 0;
    }   
       delete _reader_thd
}

但这仍然会导致同样的错误。这段代码在这个过程中被多次调用。

似乎有两个变量被称为
\u pid
——您在构造函数中声明的本地变量:

pid_t _pid;  //here the var is declared
以及你在析构函数中访问的那个:

if (_pid > 0)   //valgrind is reporting that the error is here!!
这些变量不同:在析构函数中访问的变量必须是全局变量或实例变量(更可能)

由于依赖于
\u pid
将状态从构造函数传递到析构函数,因此需要从构造函数中删除本地声明,并根据需要初始化另一个
\u pid
。如果是实例变量,请将其初始化添加到初始值设定项列表中,如下所示:

GmpPipePlayer::GmpPipePlayer( IOBase *pIO, Referee *pBack, PieceColor pc, int size, const DataBoard *pBd, int handicap, const char *cmd_line, int bDebug )
: GmpPlayer(pIO, pBack, pc, size, pBd, handicap, bDebug), _pid(0) {
    ... //                         HERE ------------------^
}
GmpPipePlayer::GmpPipePlayer( IOBase *pIO, Referee *pBack, PieceColor pc, int size, const DataBoard *pBd, int handicap, const char *cmd_line, int bDebug )
: GmpPlayer(pIO, pBack, pc, size, pBd, handicap, bDebug), _pid(0) {
    ... //                         HERE ------------------^
}