【问题标题】:Check for existence of a process in c++ using a thread使用线程检查 C++ 中是否存在进程
【发布时间】:2014-09-22 09:16:32
【问题描述】:

我正在尝试使用线程检查 C++ 中是否存在进程。 我最初在没有任何线程的情况下进行了测试,并让 main 检查是否存在。 有效。 但是突然间,当我将那部分代码放在一个线程中时,它就不起作用了。 我很困惑地看到它不起作用。 谁能告诉我为什么在线程中使用代码部分不起作用。

我对进程是否存在的初始测试程序: 编译如下:CC protest2.cc -o nothr

int main(int argc, char **argv)
{

struct stat sts;
string f=string("/proc/")+argv[1];
while(!(stat(f.c_str(), &sts) == -1 && errno == ENOENT))
{
cout<<"process exists"<<endl;
sleep(1);
}
cout<<"process Does not exist"<<endl;
return 0;

}

一个运行几秒钟然后退出的小进程。

int main() {
sleep(5);
for(int i=0;i<5;i++)
{
sleep(2);
}
}

我的第二个测试程序是否存在使用线程的进程(这不起作用): 编译如下:CC protest.cc -o thr

extern "C" void *run(void *str){

struct stat sts;
while(!(stat((char *)str, &sts) == -1 && errno == ENOENT))
{
cout<<"process exists"<<endl;
sleep(1);
}
return NULL;

}

int main(int argc,char **argv)
{
string f=string("/proc/")+argv[1];

pthread_t pid;
int res=pthread_create(&pid,NULL,run,(void *)f.c_str());
pthread_join(pid,NULL);
cout<<f<<endl;
cout<<"process Does not exist"<<endl;
return 0;
}

没有线程时的输出:

> ./a.out &
[1] 10128
> ./nothr 10128
process exists
process exists
process exists
process exists
process exists
process exists
process exists
process exists
process exists
process exists
process Does not exist
[1]  + Done                          ./a.out
> 

有线程时输出:

> ./thr 10458
process exists
process exists
process exists
process exists
process exists
process exists
process exists
process exists
process exists
process exists
process exists
process exists
process exists
process exists
process exists
process exists
process exists
process exists
process exists
process exists
process exists
process exists
process exists
process exists
^C

它一直持续到我按下 CTRL+C。

【问题讨论】:

  • 在您的线程函数while 循环条件中,您使用相同的参数重复调用!(stat((char *)str, &amp;sts) == -1。因此它永远循环。
  • 但是一旦进程不存在,while循环应该退出。这就是 while 循环中的条件所做的。
  • 在没有线程的情况下存在相同的while条件,并且正如预期的那样,只要进程退出,while就会退出。但出于好奇,为什么要在这里投反对票?
  • 可能是因为您似乎没有尝试调试您的问题。例如,您可以计算/打印传递给线程函数的字符串以确保它是正确的。
  • 您可以将检查分成两行,使用单独的临时布尔值作为结果,以查看哪些失败/成功。

标签: c++ c process pthreads


【解决方案1】:

从技术上讲,f.c_str()(在您的线程代码示例中)的有效生命周期纯粹是在 pthread_create 调用期间。因此,有可能在线程调用stat 时,传递的地址的内容已经发生了足够的变化,导致您收到ENOENT 以外的错误。这将使您的测试失败,您将永远循环。

顺便说一句,使用kill(pid, 0) 是一种更加便携和轻量级的测试进程是否存在的方法。

【讨论】:

  • 我通过在线程内打印字符串进行了检查,它显示了正确的进程 ID。
  • 该循环将继续,直到 stat 返回 -1 并且 errno 设置为 ENOENT。显然不是。所以要么您查看的 pid 错误,要么代码未发布。
猜你喜欢
  • 2014-02-18
  • 1970-01-01
  • 1970-01-01
  • 2010-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-02
相关资源
最近更新 更多