gpt4 book ai didi

c++ - 初始化 pid_t 变量

转载 作者:行者123 更新时间:2023-11-28 03:30:45 37 4
gpt4 key购买 nike

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
}

所以,我认为问题是_pid没有初始化,应该如何初始化这个变量呢?我这样试过:

 pid_t _pid=0;

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

最佳答案

您似乎有两个名为 _pid 的变量 - 您在构造函数中声明的本地变量:

pid_t _pid;  //here the var is declared

以及您在析构函数中访问的那个:

if (_pid > 0)   //valgrind is reporting that the error is here!!

这些变量并不相同:您在析构函数中访问的变量必须是全局变量或实例变量(更有可能)。

由于你依赖_pid将状态从构造函数传递到析构函数,你需要从构造函数中移除局部声明,并将另一个_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 ------------------^
}

关于c++ - 初始化 pid_t 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12700531/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com