Check for existence of a process in c++ using a thread -


i trying check existence of process in c++ using thread. tested without having thread , let main check existance. worked. when put part of code inside thread not work. puzzled see not working. please tell me why part of code not working when comes using in thread.

my initial test program existance of process: compiled below: 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 not exist"<<endl; return 0;  } 

a small process runs secs , exits.

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

my second test program existance of process using thread(this not work): compiled below: 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 not exist"<<endl; return 0; } 

output when there no thread:

> ./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 not exist [1]  + done                          ./a.out >  

output when there thread:

> ./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 

it goes on untill press ctrl+c.

very technically, valid lifetime of f.c_str() (in threaded code sample) purely duration of pthread_create call. possible @ time thread calls stat, contents of address passed have changed sufficiently cause error other enoent. fail test , you'll loop forever.

in passing, using kill(pid, 0) more portable , lightweight way of testing existence of process.


Comments

Popular posts from this blog

Python Kivy ListView: How to delete selected ListItemButton? -

asp.net mvc 4 - A specified Include path is not valid. The EntityType '' does not declare a navigation property with the name '' -