#include ONCE "window9.bi"

#define DT_UNKNOWN 0

#define DT_FIFO	1

#define DT_CHR	2

#define DT_DIR	4

#define DT_BLK	6

#define DT_REG	8

#define DT_LNK	10

#define DT_SOCK	12

#define DT_WHT 14

#define SIGKILL 9

type dirent
	
	as integer d_ino
	
	as integer d_off
	
	as unsigned short d_reclen
	
	as Ubyte d_type
	
	as zstring*256 d_name
	
End Type



extern "C"
	
	declare function opendir (szName as zstring ptr) as any ptr
	
	Declare function readdir (pOD as any ptr) as dirent ptr
	
	declare function closedir (pOD as any ptr) as integer
	
	declare function KILL_ alias "kill" ( pid as integer, sig as integer) as integer
	
	declare function waitpid (__pid as pid_t, __stat_loc as Integer ptr, __options as integer) as pid_t
	
End Extern


dim shared as dirent ptr pDirent

dim shared as string sNameProcess

dim shared as string sFullCommand

dim shared as integer iPID 


sub KillProcess( iPID as Integer , iExitCode as Integer = SIGKILL) export 
	
	kill_(iPID, iExitCode)
	
End Sub

function GetNameProcess() as string export
	
	return sNameProcess
	
End Function

function GetFullCommandProcess() as string export
	
	return sFullCommand
	
End Function

function GetIDProcess() as integer export
	
	return iPID
	
End Function

function InitProcess() as HANDLE export
	
	dim as Handle p = opendir("/proc/")
	
	if p = 0 then
		
		return cast(HANDLE,-1)
		
	else 
		
		return p
		
	EndIf
	
End Function

sub CloseHandle( pDir as HANDLE) export
	
	sFullCommand = ""
	
	sNameProcess = ""
	
	closedir(pDir)
	
End Sub

function ReadProcess(pDir as HANDLE) as Long
	
	function = 1
	
	do
		
		pDirent = readdir(pDir)
		
		if pDirent = 0 then
			
			function = 0
			
			exit do
			
		else
			
			if pDirent->d_type and DT_DIR then
				
				select case (PDirent->d_name)[0] 
					
					Case asc("0") to asc("9")
					
						iPID = val(PDirent->d_name) 	
					
						dim as HANDLE h  = Read_file("/proc/" & PDirent->d_name & "/cmdline")
					
						if h = cast(handle,-1) then exit do
					
						sNameProcess = ""					
					
						sFullCommand = trim (Read_string(h)	,  any " " & chr(9))
					
						Close_file(h)					
					
						h  = Read_file("/proc/" & PDirent->d_name & "/status")
					
						While feof(h) = 0
						
							sNameProcess = Read_string(h)
						
							var iPos = instr(lcase(sNameProcess) , "name:")
						
							if iPos then
							
								sNameProcess = trim (mid(sNameProcess , 6) ,any " " & chr(9))
							
								exit while
							
							EndIf
						
						Wend
					
						Close_file(h)
					
						exit do
					
				End Select				
				
			EndIf
			
		EndIf 
		
	loop
	
End Function

function FirstProcess( pDir as HANDLE) as Long export 
	
	return ReadProcess( pDir )
	
End Function

function NextProcess( pDir as HANDLE) as Long export 
	
	return ReadProcess( pDir )
	
End Function