File: proc.c

package info (click to toggle)
ips 4.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 664 kB
  • sloc: ansic: 10,438; makefile: 25
file content (1035 lines) | stat: -rw-r--r-- 23,090 bytes parent folder | download | duplicates (4)
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
/*
 * Configurable ps-like program.
 * Process information utility routines.
 *
 * Copyright (c) 2010 David I. Bell
 * Permission is granted to use, distribute, or modify this source,
 * provided that this copyright notice remains intact.
 */

#include "ips.h"


/*
 * Static variables.
 */
static	long	elapsedMilliseconds;		/* time between CPU percentage samples */
static	struct	timeval	currentTimeval;		/* current accurate time */
static	struct	timeval	baseTimeval;		/* accurate beginning time of current sample */
static	struct	timeval	cpuSampleTimes[PERCENT_SAMPLES];	/* times of cpu samples */


/*
 * Static procedures.
 */
static	void	ScanDeadProcesses(BOOL isThread);
static	BOOL	IsProcessRemovable(PROC * proc);
static	void	FreeProcess(PROC * proc);
static	void	RemoveOwnerThread(PROC * proc);
static	BOOL	AppendState(PROC * proc, short * countTable, int state);


/*
 * Perform the initial process scan if required, and sleep after it.
 * This is required if some columns are selected which require more than
 * one sample to calculate the value (e.g., cpu percentage), or if the
 * user wanted to only show active processes.
 */
void
InitialProcessScan(void)
{
	if (initSleepTime <= 0)
		return;

	if (activeOnly || useInitSleep)
	{
		ScanProcesses();

		sleep(initSleepTime);
	}
}


/*
 * Find the process structure with the specified pid and tid.
 * A main process has a tid value of NO_TID_ID.
 * If the process is new, then it is malloc'd and flagged as such.
 * A new process structure has mostly rubbish values.
 * The process structure is linked into the process list.
 * This deliberately does not find dead processes since a pid
 * could be immediately reused but we still want to see the
 * old process data for a while.
 */
PROC *
FindProcess(pid_t pid, pthread_t tid)
{
	PROC *	proc;
	int	index;

	/*
	 * See if the process is already in the process list.
	 * If so, return the found structure.
	 */
	for (proc = processList; proc; proc = proc->next)
	{
		if ((proc->pid == pid) && (proc->tid == tid) &&
/*			(proc->deathTime == 0) */ 1)
		{
			return proc;
		}
	}

	/*
	 * Nope, so allocate a new structure either from the free
	 * list or else using malloc.
	 */
	proc = freeProcessList;

	if (proc)
	{
		freeProcessList = proc->next;
	}
	else
	{
		proc = AllocMemory(sizeof(PROC));

		procAllocCount++;
	}

	/*
	 * Initialise some of its columns.
	 */
	proc->next = NULL;
	proc->nextThread = NULL;
	proc->owner = NULL;
	proc->pid = pid;
	proc->tid = tid;
	proc->isThread = (tid != NO_THREAD_ID);
	proc->isNew = TRUE;
	proc->isValid = FALSE;
	proc->isActive = FALSE;
	proc->isShown = FALSE;
	proc->hasCommand = FALSE;
	proc->isChanged = TRUE;
	proc->isAncient = ancientFlag;
	proc->state = ' ';
	proc->states[0] = '\0';
	proc->deathTime = 0;
	proc->startTimeTicks = 0;
	proc->startTimeClock = 0;
	proc->firstCpuTime = 0;
	proc->lastSavedTime = 0;
	proc->lastActiveTime = 0;
	proc->lastSyncTime = 0;
	proc->liveCounter = 0;
	proc->percentCpu = 0;
	proc->percentMemory = 0;
	proc->threadCount = 0;
	proc->runOrder = 0;
	proc->openFiles = 0;
	proc->endCode = 0;
	proc->oldSystemRunTime = 0;
	proc->oldUserRunTime = 0;
	proc->policy = 0;
	proc->realTimePriority = 0;
	proc->commandLength = 0;
	proc->environmentLength = 0;
	proc->rootPathLength = 0;
	proc->cwdPathLength = 0;
	proc->execPathLength = 0;
	proc->command = proc->commandBuffer;
	proc->environment = emptyString;
	proc->rootPath = emptyString;
	proc->cwdPath = emptyString;
	proc->execPath = emptyString;
	proc->stdioPaths[0] = emptyString;
	proc->stdioPaths[1] = emptyString;
	proc->stdioPaths[2] = emptyString;
	proc->program[0] = '\0';
	proc->waitChanSymbol[0] = '\0';

	/*
	 * Initialize all the cpu samples to zero.
	 */
	for (index = 0; index < PERCENT_SAMPLES; index++)
	{
		proc->cpuTable[index] = 0;
	}

	/*
	 * Add it to the process list.
	 */
	proc->next = processList;
	processList = proc;

	/*
	 * If this is a thread process then link it into the thread
	 * list of its main process.
	 */
	if (tid != NO_THREAD_ID)
	{
		PROC * mainProc = FindProcess(pid, NO_THREAD_ID);

		proc->owner = mainProc;
		proc->nextThread = mainProc->nextThread;
		mainProc->nextThread = proc;
	}

	return proc;
}


/*
 * Remove all dead processes from the process list that are older than
 * the preserve death time.  Such a delay gives the user a chance to
 * see transient processes which only appear for one process scan.
 * This is done with two passes through the process list.
 * First threads are removed, and then main processes are removed.
 */
void
RemoveDeadProcesses(void)
{
	ScanDeadProcesses(TRUE);
	ScanDeadProcesses(FALSE);
}


/*
 * Scan the process list for either main processes or thread processes
 * and check them for being dead.  If they are dead long enough then
 * they are removed.
 */
static void
ScanDeadProcesses(BOOL isThread)
{
	PROC *	proc;
	PROC *	prevProc;
	PROC *	nextProc;

	prevProc = NULL;

	for (proc = processList; proc; proc = nextProc)
	{
		/*
		 * Save the next process locally since if this process is
		 * freed its next pointer is modified.
		 */
		nextProc = proc->next;

		/*
		 * If this process is not the specified type then ignore it.
		 */
		if (proc->isThread != isThread)
		{
			prevProc = proc;

			continue;
		}

		/*
		 * Check to see if the process is dead and removable.
		 * If not then leave it in the process list.
		 */
		if (!IsProcessRemovable(proc))
		{
			prevProc = proc;

			continue;
		}

		/*
		 * The process is completely finished.
		 * Remove it from the process list by linking the previous
		 * process to the next one and leaving prevproc alone.
		 */
		if (prevProc)
			prevProc->next = nextProc;
		else
			processList = nextProc;

		/*
		 * If this is a thread process then remove it from its
		 * owner's thread list.
		 */
		RemoveOwnerThread(proc);

		/*
		 * Clear out the process structure and move it to the
		 * free list for reuse.
		 */
		FreeProcess(proc);
	}
}


/*
 * Check whether the process can be removed.
 * This is true if it is known to be dead, and if it has been
 * dead long enough.
 */
static BOOL
IsProcessRemovable(PROC * proc)
{
	/*
	 * If the process is still alive then it isn't removable.
	 */
	if (proc->liveCounter == liveCounter)
		return FALSE;

	/*
	 * The process is dead.
	 * Clear some of its state to look good in status displays.
	 * It's unclear how much of this should be cleaned out...
	 */
	proc->state = ' ';
	proc->oldState = ' ';
	proc->states[0] = '\0';
	proc->oldUserRunTime = proc->userRunTime;
	proc->oldSystemRunTime = proc->systemRunTime;
	proc->percentCpu = 0;
	proc->percentMemory = 0;
	proc->pagesSwapped = 0;
	proc->virtualSize = 0;
	proc->rss = 0;

	/*
	 * Update the cpu percentage used for the process since it
	 * is still useful to see that change for a dead process.
	 */
	CalculateCpuPercentage(proc);

	/*
	 * If the process has just been noticed as being dead
	 * then remember that time, and also the fact that it was
	 * last active then (since it had to run to disappear).
	 */
	if (proc->deathTime == 0)
	{
		proc->deathTime = currentTime;
		proc->lastActiveTime = currentTime;
		proc->runOrder = liveCounter;
	}

	/*
	 * If the process is dead recently enough, then leave it
	 * alone for a while so that the user can still see it.
	 */
	if ((deathTime > 0) &&
		(currentTime <= proc->deathTime + deathTime))
	{
		return FALSE;
	}

	/*
	 * If this is a main process which still has some thread
	 * processes then leave it (but this should not happen!).
	 */
	if (!proc->isThread && (proc->nextThread != 0))
		return FALSE;

	/*
	 * The process can be removed.
	 */
	return TRUE;
}


/*
 * Remove the specified thread (if applicable) from its owner thread list.
 */
static void
RemoveOwnerThread(PROC * proc)
{
	PROC *	testProc;

	/*
	 * If this isn't a thread then do nothing.
	 */
	if (!proc->isThread || (proc->owner == 0))
		return;

	/*
	 * Remove this process from the owner's thread list.
	 */
	testProc = proc->owner->nextThread;

	if (testProc == proc)
	{
		proc->owner->nextThread = proc->nextThread;

		return;
	}

	while (testProc)
	{
		if (testProc->nextThread == proc)
		{
			testProc->nextThread = proc->nextThread;

			return;
		}

		testProc = testProc->nextThread;
	}
}


/*
 * Free any storage associated with a process structure and move it
 * onto the process free list.  Any unlinking of the structure from
 * other processes or the process list has to be done first.
 */
static void
FreeProcess(PROC * proc)
{
	/*
	 * Clear a bit of state just in case.
	 */
	proc->next = 0;
	proc->owner = 0;
	proc->nextThread = 0;
	proc->isValid = FALSE;
	proc->pid = 0;
	proc->tid = 0;
	proc->state = ' ';
	proc->states[0] = '\0';

	/*
	 * Free any dynamic storage used by the process.
	 */
	if (proc->command != proc->commandBuffer)
	{
		free(proc->command);
		proc->command = proc->commandBuffer;
	}

	proc->commandLength = 0;

	FreeSharedString(proc->environment);
	proc->environment = emptyString;
	proc->environmentLength = 0;

	FreeSharedString(proc->cwdPath);
	proc->cwdPath = emptyString;
	proc->cwdPathLength = 0;

	FreeSharedString(proc->rootPath);
	proc->rootPath = emptyString;
	proc->rootPathLength = 0;

	FreeSharedString(proc->execPath);
	proc->execPath = emptyString;
	proc->execPathLength = 0;

	FreeSharedString(proc->stdioPaths[0]);
	FreeSharedString(proc->stdioPaths[1]);
	FreeSharedString(proc->stdioPaths[2]);

	proc->stdioPaths[0] = emptyString;
	proc->stdioPaths[1] = emptyString;
	proc->stdioPaths[2] = emptyString;

	/*
	 * Add the process structure to the free process list.
	 */
	proc->next = freeProcessList;
	freeProcessList = proc;
}


/*
 * Calculate how long it has been since the process has been active.
 * Part of this calculation compares previously gathered state with
 * the newest state.  In this way, even transiently running processes
 * can still be detected as not being idle.
 */
void
CheckActiveProcess(PROC * proc)
{
	BOOL	isActive;

	/*
	 * The process is definitely active if it is currently runnable
	 * or is in a short term wait like disk I/O.
	 */
	isActive = ((proc->state == 'R') || (proc->state == 'D'));

	if (isActive)
	{
		proc->lastActiveTime = currentTime;
		proc->runOrder = liveCounter;
	}

	/*
	 * Recalculate the CPU and memory percentages.
	 */
	CalculateCpuPercentage(proc);

	if (totalMemoryClicks > 0)
	{
		proc->percentMemory =
			(proc->rss * MEMORY_SCALE) / totalMemoryClicks;
	}

	proc->isChanged = FALSE;

	/*
	 * If some of its state has changed since the last check,
	 * then it is also considered active.  Save the new values
	 * of that state for future checks.
	 */
	if (proc->isNew ||
		(proc->userRunTime != proc->oldUserRunTime) ||
		(proc->systemRunTime != proc->oldSystemRunTime) ||
		(proc->state != proc->oldState) ||
		(proc->flags != proc->oldFlags) ||
		(proc->minorFaults != proc->oldMinorFaults) ||
		(proc->majorFaults != proc->oldMajorFaults) ||
		(proc->startTimeTicks != proc->oldStartTimeTicks) ||
		(proc->endCode != proc->oldEndCode) ||
		(proc->esp != proc->oldEsp) ||
		(proc->eip != proc->oldEip) ||
		(proc->waitChan != proc->oldWaitChan))
	{
		proc->isChanged = TRUE;
		proc->isNew = FALSE;
		proc->isAncient = ancientFlag;
		proc->lastActiveTime = currentTime;
		proc->lastSavedTime = currentTime;
		proc->runOrder = liveCounter;
		proc->oldState = proc->state;
		proc->oldFlags = proc->flags;
		proc->oldMinorFaults = proc->minorFaults;
		proc->oldMajorFaults = proc->majorFaults;
		proc->oldUserRunTime = proc->userRunTime;
		proc->oldSystemRunTime = proc->systemRunTime;
		proc->oldStartTimeTicks = proc->startTimeTicks;
		proc->oldEndCode = proc->endCode;
		proc->oldEsp = proc->esp;
		proc->oldEip = proc->eip;
		proc->oldWaitChan = proc->waitChan;
	}

	/*
	 * If the state changed recently, then the process is still active.
	 * Don't do this check for ancient processes that were there
	 * before we knew about their idleness.
	 */
	if ((!proc->isAncient) &&
		(currentTime <= (proc->lastSavedTime + activeTime)))
	{
		isActive = TRUE;
	}

 	if (isActive)
		proc->isAncient = FALSE;

	proc->isActive = isActive;
}


/*
 * Calculate the CPU percentage of a process.  This uses the sample times
 * table and the cpu runtime sample table of the process.  This should be
 * called soon after UpdateTimes has been called and soon after the new
 * runtime of the process has been found.
 */
void
CalculateCpuPercentage(PROC * proc)
{
	long	oldCpuTime;
	long	ticksUsed;
	double	percentage;

	/*
	 * Update the cpu time of the process for the current sample.
	 */
	proc->cpuTable[newCpuIndex] = proc->userRunTime + proc->systemRunTime;

	/*
	 * If we don't have any samples yet then the percentage is zero.
	 */
	proc->percentCpu = 0;

	if (elapsedMilliseconds <= 0)
		return;

	/*
	 * Calculate the ticks used by the process between the old and the
	 * new samples.  If we don't have the runtime for the beginning
	 * sample time then use the process's first seen runtime.
	 */
	oldCpuTime = proc->cpuTable[oldCpuIndex];

	if (oldCpuTime < proc->firstCpuTime)
		oldCpuTime = proc->firstCpuTime;

	ticksUsed = proc->cpuTable[newCpuIndex] - oldCpuTime;

	if (ticksUsed <= 0)
		return;

	/*
	 * Calculate the percentange of the CPU used from the ticks used and
	 * and the elapsed time of the sample.  Do this using floating point
	 * since otherwise it can overflow.
	 */
	percentage = ticksUsed;
	percentage *= 1000;
	percentage *= CPU_SCALE;
	percentage /= ticksPerSecond;
	percentage /= elapsedMilliseconds;

	proc->percentCpu = (int) percentage;
}


/*
 * Update the current time and determine whether or not it is time for a
 * new CPU sample to be taken for the processes.  This provides a rolling
 * CPU percentage feature based on the last few seconds which is much
 * better than an "instantaneous" CPU percentage.
 */
void
UpdateTimes(void)
{
	/*
	 * Increment the live counter and get the current time.
	 */
	liveCounter++;

	GetTimeOfDay(&currentTimeval);

	currentTime = currentTimeval.tv_sec;

	/*
	 * If this is the first call then initialize the times.
	 */
	if (baseTimeval.tv_sec == 0)
	{
		baseTimeval = currentTimeval;
		cpuSampleTimes[0] = currentTimeval;
		cpuSampleTimes[1] = currentTimeval;
		oldCpuIndex = 0;
		newCpuIndex = 1;
	}

	/*
	 * See how much time has elapsed since the start of the current
	 * CPU sample interval.
	 */
	elapsedMilliseconds = ElapsedMilliSeconds(&baseTimeval, &currentTimeval);

	/*
	 * If enough time has gone by then start a new sample.
	 * (But don't do this if we would catch up to the old index.)
	 */
	if (elapsedMilliseconds * PERCENT_RESOLUTION >= 1000)
	{
		int tempIndex = (newCpuIndex + 1) % PERCENT_SAMPLES;

		if (tempIndex != oldCpuIndex)
		{
			newCpuIndex = tempIndex;

			/*
			 * Store the beginning time of the sample.
			 */
			baseTimeval = currentTimeval;
		}
	}

	/*
	 * Update the time of the current sample.
	 */
	cpuSampleTimes[newCpuIndex] = currentTimeval;

	/*
	 * Advance the old CPU index value if we can so that the
	 * elapsed interval is only as large as desired.
	 */
	while (oldCpuIndex != newCpuIndex)
	{
		int tempIndex = (oldCpuIndex + 1) % PERCENT_SAMPLES;

		if (tempIndex == newCpuIndex)
			break;

		elapsedMilliseconds = ElapsedMilliSeconds(
			&cpuSampleTimes[tempIndex], &currentTimeval);

		if (elapsedMilliseconds < percentSeconds * 1000)
			break;

		oldCpuIndex = tempIndex;
	}

	/*
	 * Save the elapsed milliseconds between the old sample time
	 * and the current time.  This is the interval used for the
	 * CPU percentage calculations.
	 */
	elapsedMilliseconds = ElapsedMilliSeconds(
		&cpuSampleTimes[oldCpuIndex], &currentTimeval);
}


/*
 * Update the total number of processes and threads which are being shown.
 * This should only be called after the status of the processes has been
 * completed for a cycle, so that dead processes are removed and the isShown
 * flags for the processes are accurate.
 * Note: The total number of processes and threads is NOT updated here
 * since we don't necessarily scan all of the processes and so the list
 * of PROC structures doesn't have all of the needed information.
 */
void
UpdateProcessCounts(void)
{
	const PROC *	proc;

	procShowCount = 0;
	threadShowCount = 0;

	/*
	 * Loop over all of the processes (and maybe the threads).
	 */
	for (proc = processList; proc; proc = proc->next)
	{
		/*
		 * If this is a thread then increment the thread count.
		 */
		if (proc->isThread)
		{
			if (proc->isShown)
				threadShowCount++;

			continue;
		}

		/*
		 * This is a main process structure.
		 * Increment the process count.
		 */
		if (proc->isShown)
			procShowCount++;

		/*
		 * If the thread information is not being collected
		 * or if there is only one thread for the process
		 * then we must increment the thread count specially.
		 * (Only the main thread of the process is seen.)
		 */ 
		if ((proc->threadCount <= 1) ||
			(!useThreads && !showThreads))
		{
			if (proc->isShown)
				threadShowCount++;
		}
	}
}


/*
 * Store a command line string into the process structure.
 * The len value is the length of the string without the
 * terminating null character.
 */
void
SetCommandLine(PROC * proc, const char * str, int len)
{
	/*
	 * See if the old and new commands are empty.
	 */
	if ((len == 0) && (proc->commandLength == 0))
		return;

	/*
	 * See if the command line is the same as last time.
	 * If so, then we are done.
	 */
	if ((len == proc->commandLength) &&
		(str[0] == proc->command[0]) &&
		(str[len - 1] == proc->command[len - 1]) &&
		(memcmp(str, proc->command, len) == 0))
	{
		return;
	}

	/*
	 * Free any old command line buffer that was there, and point
	 * back to the space already allocated in the proc structure.
	 */
	if (proc->command != proc->commandBuffer)
		free(proc->command);

	proc->command = proc->commandBuffer;

	/*
	 * If the command line is too large for the proc buffer,
	 * then allocate a new one.  (The buffer has a couple of
	 * extra bytes for the terminating null.)
	 */
	if (len > BUF_COMMAND_LEN)
		proc->command = AllocMemory(len + 1);

	/*
	 * Copy the command line into the command buffer and set its length.
	 */
	memcpy(proc->command, str, len);
	proc->command[len] = '\0';
	proc->commandLength = len;
}


/*
 * Set a shared string value with its length into the specified locations 
 * (generally for one of the values in a PROC structure).  The new string is
 * compared with the existing one, and if it differs, the previous string
 * value is freed and the new one is stored.  Returns TRUE on success or
 * FALSE on an error with an empty string stored.
 */
BOOL
SetSharedString(char ** saveStr, int * saveLen, const char * str, int len)
{
	/*
	 * Get convenient references to the old strings.
	 */
	char * oldStr = *saveStr;
	int oldLen = *saveLen;

	/*
	 * If the old and new strings are both empty then there is
	 * nothing to do.
	 */
	if ((oldLen == 0) && (len == 0))
		return TRUE;

	/*
	 * Compare the new string against what is already there.
	 * If they are the same, then we don't need to do anything.
	 */
	if ((oldLen == len) &&
		(oldStr[0] == str[0]) &&
		(oldStr[len - 1] == str[len - 1]) &&
		(memcmp(oldStr, str, len) == 0))
	{
		return TRUE;
	}

	/*
	 * The value is being changed.
	 * Free the old one and try to allocate the new one.
	 */
	FreeSharedString(oldStr);

	*saveStr = AllocateSharedString(str, len);
	*saveLen = len;

	if (*saveStr != NULL)
		return TRUE;

	/*
	 * The allocation failed.
	 * Set an empty value and return failure.
	 */
	*saveStr = emptyString;
	*saveLen = 0;

	return FALSE;
}


/*
 * Get the run order of the process, taking into account its threads.
 */
ULONG
GetRunOrder(const PROC * proc)
{
	ULONG	runOrder = proc->runOrder;

	if (!useThreads && !showThreads)
		return runOrder;

	if (proc->isThread || (proc->threadCount == 1))
		return runOrder;

	for (proc = proc->nextThread; proc; proc = proc->nextThread)
	{
		if (runOrder < proc->runOrder)
			runOrder = proc->runOrder;
	}

	return runOrder;
}


/*
 * Get the last active time of the process, taking into account its threads.
 */
time_t
GetLastActiveTime(const PROC * proc)
{
	time_t	lastActiveTime = proc->lastActiveTime;

	if (!useThreads && !showThreads)
		return lastActiveTime;

	if (proc->isThread || (proc->threadCount == 1))
		return lastActiveTime;

	for (proc = proc->nextThread; proc; proc = proc->nextThread)
	{
		if (lastActiveTime < proc->lastActiveTime)
			lastActiveTime = proc->lastActiveTime;
	}

	return lastActiveTime;
}


/*
 * Get whether the process is active, taking into account its threads.
 */
BOOL
GetIsActive(const PROC * proc)
{
	if (proc->isActive)
		return TRUE;

	if (!useThreads && !showThreads)
		return FALSE;

	if (proc->isThread || (proc->threadCount == 1))
		return FALSE;

	for (proc = proc->nextThread; proc; proc = proc->nextThread)
	{
		if (proc->isActive)
			return TRUE;
	}

	return FALSE;
}


/*
 * Get the state character of the process, taking into account its threads.
 * We have a hierarchy of states.
 */
int
GetState(const PROC * proc)
{
	int	state = proc->state;

	if (!useThreads && !showThreads)
		return state;

	if (proc->isThread || (proc->threadCount == 1))
		return state;

	for (proc = proc->nextThread; proc; proc = proc->nextThread)
	{
		state = PickBestState(state, proc->state);
	}

	return state;
}


/*
 * Build and save a string describing the list of thread states for the process.
 * The single character states can be followed by a numeric count as in "R4DS3".
 */
void
BuildStates(PROC * proc)
{
	int	state;
	PROC *	threadProc;
	short	countTable[128];

	/*
	 * Get the single process state and use that if there are no
	 * threads or we are a thread.
	 */
	proc->states[0] = proc->state;
	proc->states[1] = '\0';

	if (!useThreads && !showThreads)
		return;

	if (proc->isThread || (proc->threadCount == 1))
		return;

	/*
	 * Calculate a table of counts for the threads indexed by each of
	 * their state letters.
	 */
	memset(countTable, 0, 128 * sizeof(short));

	for (threadProc = proc->nextThread; threadProc;
		threadProc = threadProc->nextThread)
	{
		countTable[threadProc->state & 0x7f]++;
	}

	/*
	 * Format and append the state count values in a nice order.
	 */
	proc->states[0] = '\0';

	AppendState(proc, countTable, 'R');
	AppendState(proc, countTable, 'D');
	AppendState(proc, countTable, 'S');
	AppendState(proc, countTable, 'T');

	/*
	 * Append any other leftover states.
	 */
	for (state = ' '; state < 128; state++)
		AppendState(proc, countTable, state);
}


/*
 * Format and append a state with its count value and clear the value.
 * Returns TRUE if the state could be stored.
 */
static BOOL
AppendState(PROC * proc, short * countTable, int state)
{
	int	count;
	int	len;
	char	buf[20];

	count = countTable[state];

	if (count == 0)
		return TRUE;

	countTable[state] = 0;

	len = strlen(proc->states);

	if (count == 1)
	{
		if (len >= MAX_STATES_LEN)
			return FALSE;

		proc->states[len++] = state;
		proc->states[len] = '\0';

		return TRUE;
	}

	sprintf(buf, "%c%d", state, count);

	if (len + strlen(buf) >= MAX_STATES_LEN)
		return FALSE;

	strcpy(&proc->states[len], buf);

	return TRUE;
}

/* END CODE */