The following conventions are used throughout this document.
argname a required argument.
[argname] an optional argument.
(out) argname an output argument, typically requires a reference for this argument.
All methods and functions return TRUE on success. FALSE on failure or unless otherwise noted. If an error occurs the Perl built in variable, '$!' is set. A reference to '$!' as a string will return a string explaining the error.
The Create function acts as a constructor for the Process class. The executable module ($ApplicationName) is executed and passed $CommandLine. $CommandLine is the full command line for the new process.
To execute a perl script:
$CommandLine = 'perl myscript.pl';
The options for CreateOptions are:
Option NameDescription CREATE_DEFAULT_ERROR_MODE Give the new process the default error mode. CREATE_NEW_CONSOLE The new process has a new console. This can't be used with DETACHED_PROCESS. CREATE_NEW_PROCESS_GROUP The new process is the root of a new process group. CREATE_SEPARATE_WOW_VDM The new process is run in it's own Virtual Dos Machine (VDM). Only applicable to 16-bit apps. CREATE_SUSPENDED The primary thread of the process is created in a suspended state. The process can be started with the Resume method below. CREATE_UNICODE_ENVIRONMENT The environment block of the new process uses UNICODE characters. DEBUG_PROCESS The calling process is treated as a debugger, and the new process is being debugged. DEBUG_ONLY_THIS_PROCESS If the calling process is being debugged, then the new process will not be debugged. DETACHED_PROCESS The new process does not have access to the console of the calling process. Kill($ExitCode)
Kills the process.
Suspend()
Suspend the process.
Resume()
Resume a suspended process. This call can be used to resume a process that was created with the CREATE_SUSPENDED flag.
GetPriorityClass((out)$Priority)The GetPriorityClass and SetPriorityClass methods allow control over the priority of the process. The $Priority can be one of
PriorityClass Description IDLE_PRIORITY_CLASS Indicates a process whose threads run only when the system is idle. (ex: screensaver) NORMAL_PRIORITY_CLASS Normal process scheduling. HIGH_PRIORITY_CLASS Indicates a process that performs time-critical tasks that must be executed immediately. REALTIME_PRIORITY_CLASS The highest process priority, even pre-empts OS threads.GetExitCode((out)$ExitCode)
GetExitCode can be used to find out how or if a process has exited.
Wait($Timeout)Wait for the process to exit. Wait returns FALSE if it times out. $! Is set to WAIT_FAILED in this case.
#'use' the process module. use Win32::Process; #theWin32:: module. Includes the Win32 error checking etc. # see Win32:: section for included functions. use Win32; sub Error { print Win32::FormatMessage(Win32::GetLastError()); } #Create the process object. Win32::Process::Create($ProcessObj, #object to hold process. "C:/winnt35/system32/Notepad.exe" #executable "Notepad temp.txt" #command line 0, #no inheritance. DETACHED_PROCESS, #separate process ".") || die &Error; #current dir. #Set the process priority $ProcessObj->SetPriorityClass(NORMAL_PRIORITY_CLASS) || die &Error; #Wait for the process to end. NO timeout $ProcessObj->Wait(INFINITE) || die &Error; $ProcessObj->GetExitCode($ExitCode) || die &Error; print" Notepad exited with $ExitCode\n";
The Create Function creates a semaphore object and returns the reference in the $SemaphoreObj scalar. The semaphore is created with an initial value of $InitialCount. The maximum number of accesses allowed is set to $MaxCount.
Destroy($SemaphoreObj)The DESTROY Function destroys the Semaphore object. This method is automatically called by Perl when the $SemaphoreObject scalar goes out of scope.
Methods
Wait($TimeOut )The Wait method causes the calling process to wait on the Semaphore. If the Semaphore is not released in $TimeOut milliseconds, the call returns, and the return value should be checked. For no timeout value, use the predefined constant INFINITE.
Release($ReleaseCount, (out)$lastCount)The Release Method releases a semaphore and increments the count by $ReleaseCount. The value of the Semaphore before the change is recorded in the $LastCount var.
use Win32::Semaphore; use Win32; Win32::Semaphore::Create($Sem,1,1,"Sem")||die &Error; #wait for access to the shared resource. if($Sem->Wait(INFINITE)) { #Access the shared resource here. &Access($Shared_Resource); $Sem->Release(1,$last); } else { print"Could not get access to shared resource\n"; }
The WaitForMultipleObjects is used to coordinate multiple events. The @objects array can hold objects of type: Semaphore, Mutex, Process, or ChangeNotify. If the $WaitAll var contains a true value (non zero) then the call waits for all of the objects, otherwise, it will return when the first object returns.
Win32::Semaphore::Create($Sem, 1,1,"Sem") || die $!; Win32::Mutex::Create($mut,0,"Mut") || die $!; #note: the WaitForMultipleObjects call is inherited, and # not referenced directly. Win32::Semaphore::WaitForMultipleObjects(($Sem,$mut),1, 10000) || die $!;
The IPC package is inherited by Win32::Process, Win32::Semaphore, Win32::ChangeNotify, and Win32::Mutex, it does not need to be implicitly 'use'd.
Create creates a mutex object and returns the reference in $MutexObj. If the $InitialOwner flag is set (nonzero) then the process calling the Create function has immediate ownership of the mutex. Otherwise, the mutex is available. $Name can be used by other processes in the Win32::Mutex::Open call to create an object to reference an already created mutex.
Open($MutexObj, $Name)Open creates a mutex object to access an already Created mutex. The $Name must point to an already created object or this call will fail. Methods Release() Release relinquishes ownership of the mutex, allowing anyone Waiting on the mutex to take ownership.
Wait($TimeOut)Wait causes the calling process to wait for $TimeOut milliseconds for the ownership of the mutex. If the mutex doesn't come available before the timeout, the call returns false. To specifiy and infinite timeout, set $TimeOut to INFINITE.
#Create a mutex object Win32::Mutex::Create($Mut,0, "MyMutex")|| die $!; #Use it sub EnterArea { local($mut) = @_; $mut->wait(5000)||die $!; #access away!!! $mut->Release(); }
Filter Option Description FILE_NOTIFY_CHANGE_FILE_NAME Any naming changes in the watched directory satisfy a change notification wait. Changes include renames, deletions, and creations. FILE_NOTIFY_CHANGE_DIR_NAME Any directory name changes. FILE_NOTIFY_CHANGE_ATTRIBUTES Any attribute changes FILE_NOTIFY_CHANGE_SIZE Any file-size change. The notification only occurs when the change is written to disk. If disk IO is cached, the change occurs when the cache is flushed. FILE_NOTIFY_CHANGE_LAST_WRITE Any change to the last write time for a file. See above for notes on caching. FILE_NOTIFY_CHANGE_SECURITY Any security descriptor changes in the directory.
Win32::ChangeNotify::FindFirst($cnobj, "d:/mydir/",1," FILE_NOTIFY_CHANGE_FILE_NAME") || die $!; #Wait for the change. $cnobj->FindNext(); $cnobj->Wait(INFINITE); #do something about the change. &Notify($Someone); $cnobj->Close;
Open the eventlog on the specified machine, if no server is specified, the local machine is used. An Eventlog object is returned in $EventObj.
Open a backup eventlog and return an object to control it. If $ServerName is not given the local machine is used.
Methods
ReadFlag option Description EVENTLOG_FORWARDS_READ Eventlog is read in forward chronological order. EVENTLOG_BACKWARDS_READ Eventlog is read in reverse chronological order. EVENTLOG_SEEK_READ The read begins at the record specified by the $RecordOffset parameter. Must also specify EVENT_LOG_FORWARD_READ or EVENTLOG_BACKWARDS_READ. EVENTLOG_SEQUENTIAL_READ The read continues sequentially from the last read call.
Reports an event. Implicitly calls RegisterEventSource.
The options for $Event are:
$Event Options Description EVENTLOG_ERROR_TYPE Error event EVENTLOG_WARNING_TYPE Warning event EVENTLOG_INFORMATION_TYPE Information event EVENTLOG_AUDIT_SUCCESS_TYPE Success Audit event EVENTLOG_AUDIT_FAILURE_TYPE Failure Audit event. $EventInfo contains the following: Key Value Category integer value for the category of the event (app defined) EventID ID value of the Event. Source specific, any value. Data The Raw binary data Strings Any text strings to merge
Example 1
use Win32::Eventlog; sub TEST1 { my $number, $EventLog; Win32::EventLog::Open($EventLog , "System", '') || die $!; $EventLog->GetNumber($number) || die $!; print "There are $number records in the System Event Log\n"; } TEST1
Example 2
use Win32::Eventlog; sub TEST2 { my $number, $EventLog; # open the event log. Win32::EventLog::Open($EventLog , "PerlApp", '') || die $!; # define the event to log. $Event = { 'EventType' => EVENTLOG_INFORMATION_TYPE, 'Category' => 0, 'EventID' => 0x1003, 'Data' => '', 'Strings' => "Test report", }; # report the event and check the error $EventLog->Report($Event) || die $!; } TEST2
If the key exists, then open it, otherwise create it. The User must have the security to create a key.
Set the value of the subkey of the current key to be $value.
Sets $value, and $type for the specific name value in the current key.
Get the information from the current key.
Return a list of character strings representing subkeys of the current key.
Save registry from current location. Set the security attributes of the file to the
Load a registry file.
use Win32::Registry; $HKEY_LOCAL_MACHINE->Open($NewObj, "MyKey") || die $!; $NewObj->SetValue("MySubKey", REG_SZ, 5);
Return the name of the domain controller for server
Gets password, passwordAge, privilege, homeDir, comment, flags,and scriptPath for user.
Sets password, passwordAge, privilege, homeDir, comment, flags,and scriptPath for user
Creates a group
Delete a group from the server.
Gets the comment for the group $group on the server $server.
Sets the comment for the group $groupName on the server $server.
Adds users to a group.
Deletes a list of users from a group.
Returns TRUE if $user is a member of $groupName
Fills userArray with the members of groupName
use Win32::NetAdmin; # set info for the user. $userName = 'TestUser'; $password = ''; $passwordAge = 0; $privilege = USER_PRIV_USER; $homeDir = 'c:\\'; $comment = 'This is a test user'; $flags = UF_SCRIPT; $scriptpath = 'C:\\'; $groupName = 'TestGroup'; $groupComment = "This is a test group"; Win32::NetAdmin::UserCreate('', $userName, $password, $passwordAge, $privilege, $homeDir, $comment, $flags, $scriptpath) || print "not "; Win32::NetAdmin::UserGetAttributes('',$userName, $Getpassword, $GetpasswordAge, $Getprivilege, $GethomeDir, $Getcomment, $Getflags, $Getscriptpath) || warn(); ($password eq $Getpassword) || warn(); ($passwordAge == $GetpasswordAge) || warn(); ($homeDir eq $GethomeDir) || warn(); ($comment eq $Getcomment) || warn(); ($flags == ($Getflags&USER_PRIV_MASK)) || warn(); ($scriptpath eq $scriptpath) || warn();
The Win32::NetAdmin module is to allow control over the Windows NT users and group functions. These are not available on Windows 95. The module will not load on a Windows95 machine.
$FileAttributes contains one or more of the following values:
Set the attributes for the listed file.
use Win32::File; Win32::File::GetAttributes("myfile.txt", $Attributes) || die $!; Win32::File::SetAttributes("myfile.txt", ($Attributes | READONLY)) || die $!;
Starts a service. This service must be registered with the Service Control Manager .
Stops a service.
The GetStatus call returns the status as a hash reference in $status.
The keys of this hash are:
These keys correspond to the members of the SERVICE_STATUS structure. (refer to the Win32 Programmer's Reference V4).
This Pair of calls pause and resume services. (Service must be able to pause.)
GetServices returns a list of available services in @$list.
use Win32::Service; Win32::Service::GetServices('', \%list) || die $!; print "Display Name = Service Name\n"; foreach $key (keys %list) { print $key, '=', $list{$key}, "\n"; } print "\n\n\n"; Win32::Service::GetStatus('', 'Messenger', \%status) || die $!; foreach $key (keys %status) { print $key, '=', $status{$key}, "\n"; }
%SHARE_INFO
The ShareInfo hash is used to pass information to the NetResource functions concerned with shares.
KEY VALUE 'netname' => Name of the share. 'type' => Type of share. 'remark' => A string comment. 'permissions' => Permissions value 'maxusers' => The max # of users. 'current-users' => The current # of users. 'path' => The path of the share. 'passwd' => A password if one is req'd
NETRESOURCE
KEY VALUE 'Scope' => Scope of an Enumeration. See Scopes below. 'Type' => The type of resource to Enum. See Types below. 'DisplayType' => The way the resource should be displayed.See Display below. 'Usage' => Specifies the Resources usage: see Usage below. 'LocalName' => Name of the local device the resource is connected to. 'RemoteName' => The network name of the resource. 'Comment' => A string comment. 'Provider' => Name of the provider of the resource. Scope values: RESOURCE_CONNECTED The resource is already connected. RESOURCE_REMEMBERED The resource is reconnected each time the user logs on. RESOURCE_GLOBALNET The resource is available to the entire network. Type values: RESOURCETYPE_ANY All resources RESOURCETYPE_DISK Disk resources RESOURCETYPE_PRINT Print resources Display Type: RESOURCEDISPLAYTYPE_DOMAIN The object should be displayed as a domain. RESOURCEDISPLAYTYPE_SERVER The object should be displayed as a server RESOURCEDISPLAYTYPE_SHARE The object should be displayed as a sharepoint. RESOURCEUSAGE_CONNECTABLE The resource can be connected to a local device. RESOURCEUSAGE_CONTAINER The resource contains more resources.
Creates a list in @Resources of %NETRESOURCE hash references.This list contains all network resources. (Shared printers, disks, etc).
Makes a connection to a network resource specified by %NETRESOURCE, for the user $user.The $Connection flag determines whether the connection should be remembered for the user, for all logins.
Cancels a connection to a network resource connected to local device $name.$Connection is either 1 - persistent connection or 0, non-persistent.
Gets the Extended Network Error. This is only applicable if Win32::GetLastError() returns ERROR_EXTENDED_ERROR.
Gets the last Error for a Win32::NetResource call.
Returns the UNC name of the disk share connected to $LocalPath in $UNCName.
NOTE: The $servername arg is optional for all of the Share calls.
Offer a disk resource for sharing on the network.
Check if a share is available for connection. The value in $type is only valid if the funtion returns a true value (non-zero).
Remove a share from a machine's list of shares.
Get the %SHARE_INFO information about the share $netname on the server $servername.
Set the information for share $netname.
use Win32::NetResource; use Win32; $ShareInfo = { 'path' => 'e:\\temp', 'netname' => "myshare", 'remark' => "This mine, leave it alone", 'passwd' => "", 'current-users' => 0, 'permissions' => 0, 'maxusers' => 10, 'type' => 10 }; Win32::NetResource::NetShareAdd($ShareInfo, $parm) || warn(); $NewShare = {}; Win32::NetResource::NetShareGetInfo("Temp", $NewShare) || warn(); $Aref=[]; Win32::NetResource::GetSharedResources($Aref, 0); # try to connect to the Temp share. # Find the NETRESOURCE information for the Temp share. foreach $href (@$Aref) { $myRef = $href if($href->{'RemoteName'} =~ /Temp/); } $myRef->{'LocalName'} = "Z:"; Win32::NetResource::AddConnection($myRef, $passwd, $user, 0); Win32::NetResource::GetUNCName($UNCName, "Z:"); print "UNCName of the share is $UNCName\n"); Win32::NetResource::CancelConnection("Z:", 0, 1); Win32::NetResource::NetShareDel("Temp") || print "not ";