File: CheckProcessUtil.cpp

package info (click to toggle)
tango 7.2.6%2Bdfsg-14
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 20,720 kB
  • sloc: cpp: 122,899; sh: 11,304; ansic: 1,079; makefile: 843; java: 215; python: 55
file content (1041 lines) | stat: -rw-r--r-- 27,738 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
static const char *RcsId = "$Header$";
//+=============================================================================
//
// file :         CheckProcessUtil.cpp
//
// description :  C++ source for the CheckProcessUtil
//
// project :      TANGO Device Server
//
// $Author: pascal_verdier $
//
// Copyright (C) :      2004,2005,2006,2007,2008,2009,2010
//						European Synchrotron Radiation Facility
//                      BP 220, Grenoble 38043
//                      FRANCE
//
// This file is part of Tango.
//
// Tango is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// Tango is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with Tango.  If not, see <http://www.gnu.org/licenses/>.
//
// $Revision: 15177 $
//
// $Log$
// Revision 3.15  2010/10/15 06:20:32  pascal_verdier
// Copyright added.
//
// Revision 3.14  2010/09/21 12:18:57  pascal_verdier
// GPL Licence added to header.
//
// Revision 3.13  2010/08/09 06:52:25  pascal_verdier
// Patch for Python module added (thanks to Tiago).
//
// Revision 3.12  2010/02/09 15:09:49  pascal_verdier
// Define  _TG_WINDOWS_  replace WIN32.
// LogFileHome property added.
//
// Revision 3.11  2008/12/12 13:30:44  pascal_verdier
// Problem on python server options fixed.
//
// Revision 3.10  2008/06/18 08:17:03  pascal_verdier
// Pb with case unsensitive on win32 fixed.
//
// Revision 3.9  2008/06/06 07:56:50  pascal_verdier
// Case unsensitive on instance name added.
//
// Revision 3.8  2008/06/04 09:08:03  pascal_verdier
// javaw process control added.
// Java -cp classpath parsing mmodified.
//
// Revision 3.7  2008/05/15 08:07:18  pascal_verdier
// TangoSys_MemStream replaced by TangoSys_OMemStream
// (for leaking problem under win32)
//
// Revision 3.6  2008/04/28 12:36:09  pascal_verdier
// Eception in solaris modified.
//
// Revision 3.5  2008/04/24 06:33:52  pascal_verdier
// Bug in solaris management fixed.
//
// Revision 3.4  2008/04/10 12:15:05  jensmeyer
// Added compile options for MacOSX and FreeBSD
//
// Revision 3.3  2008/04/09 14:39:57  pascal_verdier
// Better trace on pread failed
//
// Revision 3.2  2008/03/03 13:26:15  pascal_verdier
// is_process_running() method added.
//
// Revision 3.1  2008/02/29 15:15:05  pascal_verdier
// Checking running processes by system call added.
//
//-=============================================================================



#include <CheckProcessUtil.h>

#ifndef	TIME_VAR
#ifndef _TG_WINDOWS_

#	define	TimeVal	struct timeval
#	define	GetTime(t)	gettimeofday(&t, NULL);
#	define	Elapsed(before, after)	\
		1000.0*(after.tv_sec-before.tv_sec) + \
		((double)after.tv_usec-before.tv_usec) / 1000

#else

#	define	TimeVal	struct _timeb
#	define	GetTime(t)	_ftime(&t);
#	define	Elapsed(before, after)	\
		1000*(after.time - before.time) + (after.millitm - before.millitm)

#endif	/*	_TG_WINDOWS_		*/
#endif	/*	TIME_VAR	*/


namespace Starter_ns
{
//=============================================================
//=============================================================
ProcessData::ProcessData()
{
#ifdef _TG_WINDOWS_
	//	Under win 2000 or before the process name is shorted to 15 char
	//	If win 2000, take it from command line.
	win2000 = isWin2000();
#endif	/*	_TG_WINDOWS_		*/
}
//=============================================================
//=============================================================
ProcessData::~ProcessData()
{
	//	clear previous list
	for (unsigned int i=0 ; i<proc_list.size() ; i++)
		delete proc_list[i];
	proc_list.clear();
}

#ifdef _TG_WINDOWS_
//=============================================================
//=============================================================
string  ProcessData::parseNameFromCmdLine(string name, string cmdline)
{
	//	Search last position of name
	string::size_type	pos = 0;
	string::size_type	tmp;
	while ((tmp=cmdline.find(name, pos+1))!=string::npos)
		pos = tmp;

	//	Get name before sppace char
	string::size_type	end = cmdline.find(" ", pos);
	if (end==string::npos)
		end = cmdline.find("\t", pos);
	string	full_name = cmdline.substr(pos, end-pos);

	//	Take off extention if any
	end = full_name.find(".");
	if (end==string::npos)
		return full_name;
	else
		return full_name.substr(0, end);
}
//=============================================================
//=============================================================
bool ProcessData::isWin2000(void)
{
	OSVERSIONINFOEX osvi;
	BOOL bOsVersionInfoEx;

	ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
	osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
	if(!(bOsVersionInfoEx=GetVersionEx((OSVERSIONINFO *)&osvi)))
	{
		osvi.dwOSVersionInfoSize=sizeof(OSVERSIONINFO);
		if (!GetVersionEx((OSVERSIONINFO *)&osvi) )
			return true;
	}
	double	osversion = osvi.dwMajorVersion + (1.0*osvi.dwMinorVersion/10);
	if (osversion<5.1)
	{
		cout << "/=======================================" << endl;
		cout << "	Windows 2000 or before !!!" << endl;
		cout << "/=======================================" << endl;
		return true;
	}
	else
	{
		cout << "Windows XP or later" << endl;
		return false;
	}
}
//=============================================================
//=============================================================
string ProcessData::wchar2string(WCHAR *wch, int size)
{
	char	*ch = new char[size+1];
	int	i;
	for (i=0 ; wch[i]!=0 && i<size ; i++)
		ch[i] = wch[i];
	ch[i] = 0x0;
	string	str(ch);
	delete ch;
	return str;
}
//=============================================================
//=============================================================
WCHAR *ProcessData::string2wchar(string str)
{
	char	*ch  = new char[str.length()+1];
	WCHAR	*wch = new WCHAR[str.length()+1];
	strcpy(ch, str.c_str());

	int	i;
	for (i=0 ; ch[i]!=0 ; i++)
		wch[i] = (short)ch[i];
	wch[i] = 0x0;
	delete ch;
	return wch;
}
//=============================================================
//=============================================================
void ProcessData::read_process_list_from_sys()
{
	//	clear previous list
	for (int i=0 ; i<proc_list.size() ; i++)
		delete proc_list[i];
	proc_list.clear();

	// Take a snapshot of all processes in the system.
	HANDLE	hProcessSnap = 
		CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS | TH32CS_SNAPMODULE, 0);
	if( hProcessSnap == INVALID_HANDLE_VALUE)
	{
		string desc = errorCodeToString(GetLastError(), "CreateToolhelp32Snapshot" );
		Tango::Except::throw_exception(
						(const char *)"PROCESS_LIST_FAILED",
						(const char *) desc.c_str(),
						(const char *)"Starter::get_process_list()");
	}

	// Set the size of the structure before using it.
	PROCESSENTRY32	pe32;
	pe32.dwSize = sizeof( PROCESSENTRY32 );

	// Retrieve information about the first process,
	// and exit if unsuccessful
	if( !Process32First( hProcessSnap, &pe32 ) )
	{
		string desc = errorCodeToString(GetLastError(), "Process32First" );  // Show cause of failure
		CloseHandle( hProcessSnap );     // Must clean up the snapshot object!
		Tango::Except::throw_exception(
						(const char *)"PROCESS_LIST_FAILED",
						(const char *) desc.c_str(),
						(const char *)"Starter::get_process_list()");
	}

	//	Get module ntdll
    NTQIP						*lpfnNtQueryInformationProcess;
	PROCESS_BASIC_INFORMATION	pbi;
	WCHAR	*wc = string2wchar("ntdll.dll");
	HINSTANCE	hLibrary = GetModuleHandle(wc);
	delete wc;
    if (hLibrary != NULL)
    {
        lpfnNtQueryInformationProcess = (NTQIP *)GetProcAddress(hLibrary, "ZwQueryInformationProcess");
    }
	else
    {
		string	desc = errorCodeToString(GetLastError(), "GetModuleHandle() ");
		Tango::Except::throw_exception(
						(const char *)"PROCESS_LIST_FAILED",
						(const char *) desc.c_str(),
						(const char *)"Starter::get_process_list()");
    }

	__INFOBLOCK	block;
    __PEB 		PEB;
	char		*c_cmdline = NULL;
    DWORD		dwSize=0;

	// Now walk the snapshot of processes, and
	pbi.PebBaseAddress = (PPEB)0x7ffdf000;
	do
	{
		// Retrieve the priority class.
		DWORD	dwPriorityClass = 0;
		HANDLE	hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID );
		if( hProcess != NULL )
		{
	        if (lpfnNtQueryInformationProcess != NULL)
    	        (*lpfnNtQueryInformationProcess)(hProcess, ProcessBasicInformation, &pbi, sizeof(pbi), &dwSize);

			string cmdline("");
			dwPriorityClass = GetPriorityClass( hProcess );
			if( !dwPriorityClass )
				errorCodeToString(GetLastError(), "GetPriorityClass" );

			if (ReadProcessMemory(hProcess, 
					pbi.PebBaseAddress,
					&PEB,
					sizeof(PEB),
					&dwSize))
			{
				if (ReadProcessMemory(hProcess, 
						(LPVOID)PEB.dwInfoBlockAddress,
						&block,
						sizeof(block),
						&dwSize))
				{
					WCHAR	*buff = new WCHAR[block.wMaxLength+1];
    	        	if (ReadProcessMemory(hProcess, 
									(LPVOID)block.dwCmdLineAddress, 
									buff, 
									block.wMaxLength, 
									&dwSize))
						cmdline = wchar2string(buff, dwSize);
					else
						errorCodeToString(GetLastError(), "3-ReadProcessMemory()" );
					delete buff;
				}
				else
					errorCodeToString(GetLastError(), "2-ReadProcessMemory()" );
			}
			else
				errorCodeToString(GetLastError(), "1-ReadProcessMemory()" );
			
			CloseHandle( hProcess );

			//	build process object to be added in vector
			Process	*process = new Process();

			//	Remove extention from exe name
			string	full_name = wchar2string(pe32.szExeFile);
			string::size_type	pos = full_name.find('.');
			if (pos!=string::npos)
				process->name = full_name.substr(0, pos);
			else
				process->name = full_name;

			//	Parse name frome cmd line because file manager truncate it at 15 chars
			if (win2000 && process->name.length()>13)
				process->name = parseNameFromCmdLine(process->name, cmdline);

			//	On win32 -> exe file is case unsesitive
			transform(process->name.begin(), process->name.end(),
				process->name.begin(), ::tolower);


			//	add pid and cmd line
			process->pid  = pe32.th32ProcessID;
			process->line = cmdline;
			proc_list.push_back(process);
		}
	} while ( Process32Next(hProcessSnap, &pe32) );

	CloseHandle(hProcessSnap);
}



// ============================================================================
// Win32ProcessManager::errorCodeToString
// ============================================================================
string ProcessData::errorCodeToString (DWORD err_code,  string src)
{
	WCHAR	*buff;
	string	msg;

	if(err_code != ERROR_SUCCESS)
	{
		FormatMessage( 
			FORMAT_MESSAGE_ALLOCATE_BUFFER | 
			FORMAT_MESSAGE_FROM_SYSTEM | 
			FORMAT_MESSAGE_IGNORE_INSERTS,
			NULL,
			err_code,
			0, // Default language
			(LPTSTR) &buff,	
			0,
			NULL 
			);
		msg = src + string(" failed : ");
		msg += wchar2string(buff);

		// Free the buffer.
		LocalFree(buff);
	}
	else
		msg = "No Error";

	cerr << msg << endl;

	return msg;
}



#else	//	_TG_WINDOWS_




//=============================================================
//=============================================================
void ProcessData::read_process_list_from_sys()
{
	//	clear previous list
	for (unsigned int i=0 ; i<proc_list.size() ; i++)
		delete proc_list[i];
	proc_list.clear();

	//	build processes list
	DIR		*proc = opendir ("/proc") ;
	if(proc == NULL)
	{
		string	desc;
		//	error
		switch(errno)
		{
		case EACCES: desc = "Permission denied.";
			break;
		case EMFILE: desc = "Too many file descriptors in use by process.";
			break;
		case ENFILE: desc = "Too many file are currently open in the system.";
			break;
		case ENOENT: desc = "Directory does not exist or NAME is an empty string.";
			break;
		case ENOMEM: desc = "Insufficient memory to complete the operation.";
			break;
		case ENOTDIR:desc  = "NAME is not a directory.";
			break;
		}
		Tango::Except::throw_exception(
				(const char *)"READ_PROCESS_LIST_FAILED",
				desc,
				(const char *)"Starter::get_process_list()");
		
	} 

	struct dirent	*ent;
	while (ent = readdir (proc))
	{
		if (isdigit (ent->d_name[0]))
		{
			//	Get PID
			Process	*process = new Process();
			process->pid = atoi(ent->d_name);
			try
			{
				//	if process can be read, add process object to vector
				if (manageProcFiles(process))
					proc_list.push_back(process);
				else
					delete process;
			}
			catch(Tango::DevFailed &e)
			{
				cout << "Excepion catch during manageProcFiles for pid = "
					<< process->pid << endl;
				cout << e.errors[0].desc;
				delete process;
			}
			catch(...)
			{
				cout << "Excepion catch during manageProcFiles for pid = "
					<< process->pid << endl;
				delete process;
			}
		}
	}
	closedir(proc);
}


//=============================================================
/**
 *	Manage the /proc files
 */
//=============================================================
bool  ProcessData::manageProcFiles(Process *process)
{
#if (defined linux) || (defined __darwin__) || (defined __freebsd__)

	//	Read command line file
	TangoSys_OMemStream	fname;
	fname << "/proc/" << process->pid <<"/cmdline";

	//	Read file
	ifstream	ifs((char *)fname.str().c_str());
	if (ifs)
	{
		TangoSys_OMemStream	sstr;
		sstr << ifs.rdbuf() << ends;
		ifs.close();

		//	Get command line
		process->line = sstr.str();
		//	Replace NULL with SPACE char
		string::size_type	pos;
		while ((pos=process->line.find('\0'))!=string::npos)
			process->line.replace(pos, 1, " ");
		return true;
	}
	else
	{
		cerr << fname.str() << ":	" << strerror(errno) << endl;
		return false;
	}
#else	//	solaris

	//	Read psinfo file		
	TangoSys_OMemStream	fname;
	fname << "/proc/" << process->pid <<"/psinfo";

	int				fid;
	struct psinfo	ps;	
	if ((fid=open(fname.str().c_str(), O_RDONLY))!=-1)
	{
		read(fid, (void *) &ps, sizeof(struct psinfo));
		close(fid);
		process->name = ps.pr_fname;
		
		//	Check if a real process or a shell (cannot be a server)
		if (process->name=="ssh" ||
			process->name=="bash" ||
			process->name=="sh")
			return false;

		uid_t	euid = geteuid();
		if ((euid==0) || (euid == ps.pr_euid))
		{
			/*
			 * To get the argv vector and environment variables
			 * for the process you need to be either root or the owner of the process.
			 * Otherwise you will not be able to open the processes memory.
			 */
			int fdesc;
			TangoSys_OMemStream	filepath;
			filepath << "/proc/" << process->pid <<"/as";
			if ( (fdesc = open(filepath.str().c_str(), O_RDONLY|O_NONBLOCK)) < 0 )
			{
				TangoSys_OMemStream	tms;
				tms << "Cannot open " << filepath.str() << ":	" <<
					strerror(errno) << endl;
#ifdef TRACE
				cerr << tms.str();
#endif
				Tango::Except::throw_exception(
						(const char *)"PROCESS_READ_FAILED",
						(const char *) tms.str().c_str(),
						(const char *)"Starter::manageProcFiles()");
			}
			else
			{
				//	Allocate a pointer array
				size_t	size = sizeof(char *) * (ps.pr_argc+1);
				char **argvp = (char **) malloc(size);

				//	And initialize
				if (pread(fdesc, argvp, size, ps.pr_argv)>0)
				{
					TangoSys_OMemStream	line;

					//	If argv[n] read -> append to command line
					char	buff[0x100];
					for (int n=0; n<ps.pr_argc; n++)
						if (pread(fdesc, buff ,0xFF, (off_t)argvp[n])>0)
							line << buff << " ";

					process->line = line.str();
				}
				else
				{
					free(argvp);
					close(fdesc);
					TangoSys_OMemStream	tms;
					tms << "pread failed when getting command line arguments " <<
						" from memory for process  " << process->name  << " (" <<
						filepath.str() << ")\n" << strerror(errno) << endl;
					cerr << tms.str();
					Tango::Except::throw_exception(
							(const char *)"PROCESS_READ_FAILED",
							(const char *) tms.str().c_str(),
							(const char *)"Starter::manageProcFiles()");
				}
				free(argvp);
				close(fdesc);
			}
		}
		else
		{
			//	Not Owner -> get only the  ps.pr_psargs
			process->line = ps.pr_psargs;
			close(fid);
		}
	}
	else
	{
		TangoSys_OMemStream	tms;
		tms << "open(" << fname.str() << ")  failed\n" <<  strerror(errno) << endl;
		cerr << tms.str();
		Tango::Except::throw_exception(
						(const char *)"PROCESS_READ_FAILED",
						(const char *) tms.str().c_str(),
						(const char *)"Starter::manageProcFiles()");
	}
	return true;
#endif
}
#endif	//	_TG_WINDOWS_



//=============================================================
/**
 *	Not only cpp
 *	Check for other than java and python processes
 */
//=============================================================
void ProcessData::check_cpp_process(Process* process)
{
	//	Remove path
#ifndef _TG_WINDOWS_
	if (process->line_args.size()==0)
		process->name = "";
	else
		process->name = name_from_path(process->line_args[0]);
#endif

	for (unsigned int i=1 ; i<process->line_args.size() ; i++)
		process->proc_args.push_back(process->line_args[i]);
}
//=============================================================
/**
 *	Check for  java processes
 */
//=============================================================
bool ProcessData::check_java_process(Process* process)
{
	if (process->line_args.size()==0)
		return false;
#ifdef _TG_WINDOWS_
	if (process->name!="java" &&
		process->name!="javaw")
		return false;
#else
	if (name_from_path(process->line_args[0])!="java")
		return false;
#endif

	//	Parse class and instance name
	bool	found=false;
	for (int i=process->line_args.size()-1 ; !found && i>0 ; i--)
	{
		if (process->line_args[i]!="" && process->line_args[i].c_str()[0]!='-')
		{
			if (i>1)	
			{

				//	To get class name, remove package name of previous arg
				string	full_name(process->line_args[i-1]);
				string::size_type	start = 0;
				string::size_type	end;
				while ((end=full_name.find('.', start))!=string::npos)
					start = end+1;
				//	Get last one
				process->name = full_name.substr(start);
				
				//	and take this one as instance 
				process->proc_args.push_back(process->line_args[i]);
				found = true;
			}
		}
	}
	return true;
}
//=============================================================
/**
 *	Check for  python processes
 */
//=============================================================
bool ProcessData::check_python_process(Process* process)
{
	if (process->line_args.size()==0)
		return false;
#ifdef _TG_WINDOWS_
	if (process->name!="python")
		return false;
#else
	if (name_from_path(process->line_args[0])!="python")
		return false;
#endif

	if (process->line_args.size()<2)
		return false;	//	No module loaded

	//	To get python module name
	bool found_py_module = false;
	unsigned int args_idx = 1;
	for (; args_idx < process->line_args.size()-1 ; args_idx++)
	{
	    const string &arg = process->line_args[args_idx];
	    
	    if (arg.size() == 0)
	        continue;
	    
	    if (arg[0] == '-')
	    {
	        // special python arguments that receive and additional parameter
	        if (arg.size() > 1 && (arg[1] == 'Q' || arg[1] == 'W'))
	            args_idx++; 
	        continue;
	    }
	    
	    // we reached the python file in execution
        found_py_module = true;
	    
        string::size_type start = arg.rfind('/');
        if (start == string::npos)
            start = arg.rfind('\\');
        
        if (start == string::npos)
            start = 0;
        else
            start++;

	    string::size_type end = arg.rfind(".py");
        
        if (end == string::npos)
            process->name = arg.substr(start);
        else
            process->name = arg.substr(start, end-start);
        // everything from now on is an argument
        args_idx++;
        break;
	}

    if (!found_py_module)
        return false;

	for (unsigned int i=args_idx ; i<process->line_args.size() ; i++)
		process->proc_args.push_back(process->line_args[i]);
	return true;
}
//=============================================================
//=============================================================
string ProcessData::name_from_path(string full_name)
{
	string::size_type	start = 0;
	string::size_type	end;
	while ((end=full_name.find('/', start))!=string::npos)
		start = end+1;
	//	Get last one
	return full_name.substr(start);
}
//=============================================================
//=============================================================
void ProcessData::build_server_names(Process* process)
{
	// server is a process with at least one arg
	if (process->proc_args.size()>0)
	{
		process->servname  = process->name;
		process->servname += "/";
		string	instance(process->proc_args[0]);
		transform(instance.begin(), instance.end(),
				instance.begin(), ::tolower);
		process->servname += instance;
#ifdef _TG_WINDOWS_
	//	Wain32 is case unsensitive
	transform(process->servname.begin(), process->servname.end(),
					process->servname.begin(), ::tolower);
#endif
}
	else
		process->servname  = "";
}
//=============================================================
//=============================================================




//=============================================================
/**
 *	Public method to update and build process process 
 */
//=============================================================
//#define TRACE
void ProcessData::update_process_list()
{
	omni_mutex_lock sync(*this);

	TimeVal	t0, t1;
	GetTime(t0);
	read_process_list_from_sys();
	GetTime(t1);
#ifdef TRACE
	TimeVal	t2, t3;
	double max_t = 0;
	Process	*max_t_proc;
	cout << "	Reading process list = " << Elapsed(t0, t1) << " ms" << endl;
#endif

	for (unsigned int i=0 ; i<proc_list.size() ; i++)
	{
#ifdef TRACE
		GetTime(t2);
#endif
		Process	*process = proc_list[i];

		//	Split on Space char
		string::size_type	start = 0;
		string::size_type	end;
		bool	in_cotes = false;
		while ((end=process->line.find(' ', start))!=string::npos)
		{
			string	s = process->line.substr(start, (end-start));
			start = end+1;
			//	Check if not empty
			if (s!="" && s!=" " && s!="\t")
			{
				//	Check if between cotes
				if (in_cotes==false && s.find('\"')!=string::npos) //	starting
				{
					process->line_args.push_back(s);
					in_cotes = true;
				}
				else
				if (in_cotes==true) // inside
				{
					//	Get last arg and concat with new one
					string	arg = process->line_args.back();
					arg += " " + s;
					//	And replace
					process->line_args.pop_back();
					process->line_args.push_back(arg);

					if (s.find('\"')!=string::npos) // ending
						in_cotes = false;
				}
				else
					process->line_args.push_back(s);
			}
		}
		//	Get last one
		string	s = process->line.substr(start);
		if (s!="")
			process->line_args.push_back(s);


#ifndef _TG_WINDOWS_
		if (process->line_args.size()>0)
			process->name = process->line_args[0];
		else
			process->name = "";
			
#endif

		//	Check if java or python process
		if (check_java_process(process)==false)
			if(check_python_process(process)==false)
				check_cpp_process(process);
		build_server_names(process);
#ifdef TRACE2
		cout << process->pid << "	" << process->name;
		if (process->proc_args.size()>0)
			cout << " " << process->proc_args[0];
		cout << endl;
#endif

#ifdef TRACE
		GetTime(t3);
		double	t = Elapsed(t2, t3);
		if (t>max_t)
		{
			max_t = t;
			max_t_proc = process;
		}
#endif

	}
#ifdef TRACE
	GetTime(t1);
	cout << "		total = " << Elapsed(t0, t1) << " ms" << endl;
	cout << "	max:	" << max_t << "  for " << max_t_proc->name << " (" <<
				 max_t_proc->pid << ")" << endl;
#endif

}
//=============================================================
//=============================================================
int ProcessData::get_server_pid(string argin)
{
	omni_mutex_lock sync(*this);
	for (unsigned int i=0 ; i<proc_list.size() ; i++)
	{
		Process	*process = proc_list[i];
		// server is a process with at least one arg
		if (process->proc_args.size()>0)
		{
			string	servname(process->name);
			servname += "/";
			servname += process->proc_args[0];
			//cout << servname << "==" << argin << endl;
			if (servname == argin)
				return process->pid;
		}
	}
	return -1;
}
//=============================================================
/**
 * Returs true if server running 
 */
//=============================================================
bool ProcessData::is_server_running(string argin)
{
	omni_mutex_lock sync(*this);
	for (unsigned int i=0 ; i<proc_list.size() ; i++)
	{
		Process	*process = proc_list[i];
		if (process->servname == argin)
			return true;
	}
	return false;
}
//=============================================================
/**
 * Returs true if process running (do not check instance name)
 */
//=============================================================
bool ProcessData::is_process_running(string argin)
{
	omni_mutex_lock sync(*this);
	for (unsigned int i=0 ; i<proc_list.size() ; i++)
	{
		Process	*process = proc_list[i];
		if (process->name == argin)
			return true;
	}
	return false;
}
//=============================================================
//=============================================================
vector<Process> ProcessData::get_process_list()
{
	omni_mutex_lock sync(*this);
	
	//	copy list
	vector<Process>	ret;
	for (unsigned int i=0 ; i<proc_list.size() ; i++)
	{
		Process	*p_src = proc_list[i];
		Process	process;
		Process *p_target = &process;
		*p_target = *p_src;
		ret.push_back(process);
	}

	return ret;
}
//=============================================================
//=============================================================






//=============================================================
//=============================================================
int CheckProcessUtil::get_server_pid(string argin)
{
	return data->get_server_pid(argin);
}
//=============================================================
/**
 * Returs true if server running
 */
//=============================================================
bool CheckProcessUtil::is_server_running(string argin)
{
	//	Make sure instance is lower case
	string::size_type	pos = argin.find('/');
	if (pos==string::npos)
		return false;	//	Not a server name
	pos++;
	string	dsname(argin.substr(0, pos));
#ifdef _TG_WINDOWS_
	//	Wain32 is case unsensitive
	transform(dsname.begin(), dsname.end(),
					dsname.begin(), ::tolower);
#endif
	string	instance(argin.substr(pos));
	transform(instance.begin(), instance.end(),
					instance.begin(), ::tolower);
	dsname += instance;
	return data->is_server_running(dsname);
}
//=============================================================
/**
 * Returs true if process running (do not check instance name)
 */
//=============================================================
bool CheckProcessUtil::is_process_running(string argin)
{
	return data->is_process_running(argin);
}
//=============================================================
//=============================================================
vector<Process> CheckProcessUtil::get_process_list()
{
	return data->get_process_list();
}
//=============================================================
//=============================================================
void *CheckProcessUtil::run_undetached(void *ptr)
{
	while (stop_thread==false)
	{
		try
		{
			data->update_process_list();
		}
		catch(Tango::DevFailed &e)
		{
			Tango::Except::print_exception(e);
		}
		

		//	And wait n times for next loop
		for (int i=0 ; i<2 && stop_thread==false ; i++)
		{
			omni_mutex_lock sync(*data);
			data->wait(1000);
		}
	}
	delete data;
	return NULL;
}
//=============================================================
//=============================================================


}	//	namespace