Kbase

Base de Conhecimento

Habilitando o ponto de recuperação do windows XP

Publicado por agostinhojr em 9 Agosto, 2007

To turn off Windows XP System Restore:

NOTE: These instructions assume that you are using the default Windows XP Start Menu and have not changed to the Classic Start menu. To re-enable the default menu, right-click Start, click Properties, click Start menu (not Classic) and then click OK.

1. Click Start.
2. Right-click the My Computer icon, and then click Properties.
3. Click the System Restore tab.
4. Check “Turn off System Restore” or “Turn off System Restore on all drives” as shown in this illustration:
5. Click Apply.
6. When turning off System Restore, the existing restore points will be deleted. Click Yes to do this.
7. Click OK.
8. Proceed with what you need to do; for example, virus removal. When you have finished, restart the computer and follow the instructions in the next section to turn on System Restore.

To turn on Windows XP System Restore:

1. Click Start.
2. Right-click My Computer, and then click Properties.
3. Click the System Restore tab.
4. Uncheck “Turn off System Restore” or “Turn off System Restore on all drives.”
5. Click Apply, and then click OK.

Starting System Restore From a Command Prompt in Windows XP

1. Restart your computer or turn the computer on
2. Start tapping the F8 key. The Windows Advanced Options Menu appears. If you begin tapping the F8 key too soon, some computers display a “keyboard error” message. To resolve this, restart the computer and try again.
3. Select the “Safe Mode with Command Prompt option” and press Enter
4. Log on to the computer with an administrator account
5. Type the following at the command prompt and press Enter

%systemroot%\system32\restore\rstrui.exe

6. Follow the onscreen instructions to restore your computer to an earlier time.

Re-enabling System Restore in Windows XP via the Group Policy Editor

In some cases, System Restore is disabled via the Group Policy Editor. In these cases, System Restore does not show up as a tab under My Computer Properties in Windows XP. If it doesnt show up, the question becomes how do you turn it on in the first place. To re-enable System Restore via the Group Policy Editor, follow these directions:

1) Start the Group Policy Editor by clicking on Start, Run and typing gpedit.msc in the Run box and pressing Enter
2) In the left hand column, click on Computer Configuration, Administrative Templates, System, System Restore
3) In the right hand column, set Turn off System Restore and Turn off Configuration to Disable
4) Minimize the Group Policy Editor
5) Right click on My Computer and Select Manage
6) In the right hand column, double click on Services and Applications, then Services
7) Find the System Restore Service and double-click to open
8) On the General tab set [Startup Type] to Automatic using the drop down list
9) Click the Start button to start the service
10) Close the Computer Management console
11) Maximize the Group Policy Editor and set Turn off System Restore and Turn off Configuration to Not Configured
12) Close Group Policy Editor and reboot the system.
13) Once the system is rebooted, Click on Start, Right-click on My Computer, click on Properties and the System Restore tab should appear again.

Categories:

Enviado em windows | Deixar um comentário »

Habilitar o regedit no Windows XP

Publicado por agostinhojr em 9 Agosto, 2007

Por de politicas de segurança de rede de uma empresa o regedit é desabilitado, mas existe casos em que o regedit fica desabilitado para execução pelo administrador. Caso isto ocorrá deve-se fazer o seguinte:

Carregar o Editor de politicas de grupo veja em Como usar o Editor de diretivas de grupo para gerenciar a diretiva do computador local no Windows XP.

Expanda Diretiva computador local -> Configuração do Usuário -> Modelos administrativos -> Sistema. Em Impedir acesso a ferramentas de edição do Registro altere para Desativar

Categories:

Enviado em windows | Deixar um comentário »

lp Error Messages

Publicado por agostinhojr em 4 Maio, 2007

Error Messages

This appendix provides a listing of error messages, categorized by device, that may display during setup or while operating a device.

lp Error Messages

This section provides a description of the error messages that are associated with lp commands. The following variables are used in the error messages:

file(s)

Indicates the file or files that are to be printed.

dest

Indicates the name of the destination printer.

printer-id

Indicates the request identification number of the printout. For example, myprinter-46 is the printer name followed by the request identification number.

printer-name

Indicates the name of the printer.

program-name

Indicates the program name that was executed.

user

Indicates the user who requested the printout.

These messages can be found in the printer log files if you missed them on the system console. Following each message is an explanation of the probable cause of the error and the corrective action. If you cannot correct all the error conditions you encounter, call your service representative.

dest is an illegal destination name

The dest you used is not a valid destination name. Use the lpstat -p command to list valid destination names.

file is a directory

The filename you typed is a directory and cannot be printed.

xx is not a request ID or a printer

The argument you used with the cancel command is not a valid request identification number or a printer name. Use the lpstat -t command to view a list of all the printers and requests waiting to be printed.

xx is not a request

The request identification number you used with the lpmove command is not a valid request identification number. To find out which requests are valid, use the lpstat -u command.

xx not a request ID or a destination

You used an invalid request identification number or destination with the lpstat command. To find out what is valid, use the lpstat -t command.

dest not accepting requests since date

Requests to the printer that you are trying to use have been stopped by the reject command.

Can’t access FIFO

The named pipe file /var/spool/lp/FIFO is incorrect. The mode should be 600 with the owner lp and the group lp.

lp Administrator not in password file

You must have an entry in the /etc/passwd file for lp, and you must belong to the group lp.

destination printer-name unknown

Use the accept command to enable the printer so that it can accept requests.

can’t access file xx

The mode could be wrong on your directory or the file that you are trying to access.

can’t create class xx—existing printer name

The class name you are trying to use has already been given to a printer. You need to use another name or remove the printer to use the class name.

can’t create new acceptance status file

The mode may be wrong on the /var/spool/lp directory. It should be 755 with the owner lp and the group lp.

can’t create new class file

The mode may be wrong on the /var/spool/lp directory. It should be 755 with the owner lp and the group lp.

can’t create new interface program

The mode may be wrong on the /var/spool/lp/interface directory. It should be 755 with the owner lp and the group lp.

can’t create new member file

The mode may be wrong on the /var/spool/lp/member directory. It should be 755 with the owner lp and the group lp.

can’t create new printer status file

The mode may be wrong on the /var/spool/lp/pstatus file. It should be 644 with the owner lp and the group lp.

can’t create new request directory

The mode may be wrong on the /var/spool/lp/request directory. It should be 755 with the owner lp and the group lp.

can’t create printer-name—existing class name

The printer name you are trying to use has already been used as a class name. You need to assign another name to the printer.

can’t create new output queue

The mode on the file /var/spool/lp/seqfile is incorrect. It should be 644, and the mode on the directory should be 755. The owner and the group should be lp.

can’t create new sequence number file

The mode on the file /var/spool/lp/seqfile is incorrect. It should be 644, and the mode on the directory should be 755. The owner and the group should be lp.

can’t create request file xx

The mode on the file /var/spool/lp/request/printer-name/id is incorrect. Printer-name is the name of the printer such as dqp10, and id is the request identification number. The mode of the file should be 444, and the mode of the directory should be 755. The owner and the group should be lp.

can’t fork

Either you have several processes running and are not allowed to run any more, or the system has all the processes running that it can handle. You must rerun this command later.

can’t lock acceptance status

The file /var/spool/lp/QSTATLOCK prevents more than one lp request from being taken at any one time. You must rerun this command later.

can’t lock output queue

The file /var/spool/lp/QSTATLOCK prevents more than one lp request from being printed on a printer at a time. You must rerun this command later.

can’t lock printer status

The temporary file /var/spool/lp/PSTATLOCK prevents more than one lp request from being printed on a printer at a time. You must rerun this command later.

can’t lock sequence number file

The file /var/spool/lp/SEQLOCK prevents more than one lp request from getting the next printer-id (request identification) number at one time. You must rerun this command later.

can’t move request printer-id

Printer-id is the request identification number that cannot be moved. You will probably have to change the modes on the files and directories in /var/spool/lp/request. Also, after you shut down the lp scheduler, you must manually move the request from the disabled printer directory to the new destination.

can’t open class file

The lp program is trying to access the list of classes for printers. One reason it may not be able to open the class file is that the system might have the maximum number of files open that are allowed at any one time. You can correct this by typing the command at a later time.

can’t open member file

The lp program is trying to access the list of members in the directory /var/spool/lp/member. The system could have the maximum number of files open that are allowed at any one time. You can correct this by typing the command at a later time.

can’t open xx file in MEMBER directory

There are a number of reasons why file xx in the /var/spool/lp/member directory cannot be opened. The mode on the file could be incorrect; it should be 644. The system could have the maximum number of files open that are allowed at any time; you can correct this by typing the command at a later time.

can’t open xx file in class directory

If file xx cannot be opened, it is possible that the mode on the file or directory is incorrect. The file mode should be 644, and the directory mode should be 755. Another possibility is that the system has the maximum number of files open that are allowed at any one time. The latter problem can be corrected by typing the command at a later time.

can’t open xx

You cannot print on printer xx because the mode is incorrect on the /dev/tty file. The mode should be 622.

can’t open FIFO

The mode on the named pipe file /var/spool/lp/FIFO may be incorrect. It should be 600. Or the system could have the maximum number of files open that are allowed at any one time. You can correct the latter problem by typing the command at a later time.

can’t open MEMBER directory

The mode on the directory /var/spool/lp/member could be incorrect. It should be 755. Another possibility is that the system could have the maximum number of files open that are allowed at any one time. If this is the case, try typing the command at a later time.

can’t open acceptance status file

The mode on the file /var/spool/lp/qstatus may not be correct; it should be 644. Another possibility is that the system could have the maximum number of files open that are allowed at any one time. You can correct the latter problem by typing the command at a later time.

can’t open default destination file

Check the mode on the file /var/spool/lp/default; it should be 644. If the mode is correct, it could be that the system has the maximum number of files open that are allowed at any one time. You can correct this by trying the command at a later time.

can’t open file file

You incorrectly typed the filename, or you do not have the correct modes set. If you are the owner, the mode should be at least 400.

can’t open output queue

Check the mode on the file /var/spool/lp/outputq; it should be 644. This error message could also be generated if the system has the maximum number of files open that are allowed at any one time. Try entering the command at a later time.

can’t open printer status file

The mode on the file /var/spool/lp/pstatus is incorrect; it should be 644. This message is also generated if the system has the maximum number of files open that are allowed at any one time. You can correct this by trying the command at a later time.

can’t open request directory

The mode on the directory /var/spool/lp/request is incorrect; it should be 655. The system may also have the maximum number of files open that are allowed at any one time. You can correct this by trying the command at a later time.

can’t open request file xx

The mode on the file /var/spool/lp/member/request/xx is incorrect. The mode should be 644. The system may also have the maximum number of files open that are allowed at any one time. You can correct this by trying the lpmove command at a later time.

can’t open system default destination file

The mode on the file /var/spool/lp/default is incorrect. The mode should be 644. The system may also have the maximum number of files open that are allowed at any one time. You can correct this by trying the command again at a later time.

can’t open temporary output queue

The mode on the file /var/spool/lp/outputq is incorrect. The mode should be 644. The system may also have the maximum number of files open that are allowed at any one time. You can correct this by trying the command at a later time.

can’t proceed—scheduler running

Many of the lpadmin command options cannot be executed while the scheduler is running. Stop the scheduler using the lpshut command and then try invoking the command again.

can’t read current directory

The lp and lpadmin commands cannot read the directory containing the file to be printed. The directory name may be incorrect, or you do not have read permission on that directory.

can’t remove class file

The mode may be wrong on the file /var/spool/lp/class. It should be 755. The owner and the group should be lp. The file in that directory may also have the wrong mode; it should be 644.

can’t remove printer

The mode may be wrong on the /var/spool/lp/member directory. It should be 755, and the files in that directory should be 644. Both the directory and the files should be owned by lp and the group should be lp.

can’t remove request directory

The mode may be wrong on the /var/spool/lp/request directory. It should be 755 and should be owned by lp, and the group should be lp. The directory may still have pending requests to be printed, which must be removed before the directory can be removed.

can’t set user id to lp Administrator’s user id

The lpsched and lpadmin commands can be used only when you are logged in as lp or root.

can’t unlink old output queue

The lpsched program cannot remove the old output queue. You must remove it manually by using the command

rm /var/spool/lp/outputq

can’t write to xx

The lpadmin command cannot write to device xx. The mode is probably wrong on the /dev/ttyxx or /dev/plp file. It should be 622 and owned by lp.

cannot create temp file filename

The system may be out of free space on the /var filesystem. Use the command

df /var

to determine the number of free blocks. Several hundred blocks are required to ensure that the system performs correctly.

class xx has disappeared!

Class xx was probably removed after the scheduler was started. The system may be out of free space on the /var filesystem. To find out, use the following command:

df /var

Use the lpshut command to stop the scheduler and restore the class from a backup.

class xx non-existent

The class xx may have been removed because the system is out of free space on the /var filesystem. To find out how much free space is available, use the following command:

df /var

The class will probably have to be restored from a backup.

class directory has disappeared!

The /var/spool/lp/class directory has been removed. The system may be out of free space on /var; use the df /var command to find out. The class directory contains all the data for each printer class. To restore this directory, get these files and directory from a backup.

corrupted member file

The /var/spool/lp/member directory has a corrupted file in it. You should restore the directory from backup.

default destination dest non-existent

Either the default destination is not assigned, or the printer dest has been removed. Use the lpadmin command to set up a default destination or set your LPDEST environment variable to the value of the destination.

destination dest has disappeared!

A destination printer, dest, has been removed after lpsched was started. Use the lpadmin command to remove the printer.

destination printer no longer accepting requests

The printer has been disabled using the reject command. Use the accept command to reenable the printer.

destination dest non-existent

The destination printer you specified as an argument to the accept or lpadmin command is not a valid destination name, or it was removed after the scheduler was started.

destination printer was already accepting requests

The destination printer was previously enabled. Once a printer is accepting requests, any further accept commands are ignored.

destination printer already not accepting requests

A reject command had already been sent to the printer. Use the accept command to allow the printer to start accepting requests again.

destination printer-name is not accepting requests – move in progress …

The printer has been disabled by the reject command, and requests are being moved from the disabled printer to another printer. The printer can be enabled again by the accept command.

destinations are identical

When using the lpmove command, you need to specify a printer to move the print requests from and a different printer to move the requests to.

disabled by scheduler: login terminal

The login terminal has been disabled by the lp scheduler. Use the enable command to reenable the printer.

error in printer request printer-id

Printer-id is the actual request identification number. An error has likely occurred in the printer. Check the printer and reset it if needed.

illegal keyletter xx

An invalid option, xx, was used. See the reference page for the correct options.

keyletters -xx and -yy are contradictory

This combination of options to the lpadmin program cannot be used together.

keyletter xx requires a value

The option xx requires an argument. For example, in the command line

lpadmin -m model

the argument to the -m option is the name of a model interface program.

keyletters -e, -i, and -m are mutually exclusive

These options to the lpadmin command cannot be used together. Refer to the lpadmin(1M)
reference page for information on usage.

lp: xx

In this message the variable xx could be one of several arguments. Typically, it is telling you that the default destination is not assigned.

member directory has disappeared!

The /var/spool/lp/member directory has been removed. The system is probably out of free disk space in the /var filesystem. You need to clean up the /var filesystem and then install the lp commands or retrieve them from a backup.

model xx non-existent

The name that you are using for a model interface program is not valid. A list of valid models is in the /var/spool/lp/model directory.

new printers require -v and either -e, -i, or -m

A printer must have an interface program, which is specified by -e, -i, or -m options. The -v option specifies the device file for the printer. For more information on these options, refer to the lpadmin(1M) reference page.

no destinations specified

There are no destination printers specified. Use the lpadmin command to set one up.

no printers specified

There are no printers specified. Use the lpadmin command to set one up.

non-existent printer xx in PSTATUS

A printer with the name xx is in the /var/spool/lp/pstatus file but no longer exists. Use the lpadmin command to remove the printer.

non-existent printer printer-name in class xx

The printer that you are trying to address in class xx has been removed from that class.

out of memory

The message states that there is not enough memory to contain the text to be printed.

printer printer-name already in class xx

The printer you are trying to move to class xx is already in that class. You cannot move a printer to a class that it is already in.

printer printer-name has disappeared!

The printer has been removed, and the enable command cannot find it. The printer was most likely removed after the workstation was rebooted or after the scheduler was started.

printer printer-name non-existent

Printer-name is the name of a printer that was removed after the scheduler was started. You must use the command

lpadmin -xprinter-name

printer status entry for printer has disappeared

The /var/spool/lp/pstatus file has been corrupted. You need to resubmit the printer request.

printer printer-name was not busy

The printer is not printing a request at this time. Either the request you wanted to cancel is finished printing or you have specified the wrong printer.

request printer-id non-existent

You are attempting to cancel a request that does not exist. You may have given the wrong printer name or wrong request ID number, or the request may have finished printing.

request not accepted

The request was not accepted by lp. The scheduler may not be running. Use the lpstat -t command to find out more information.

requests still queued for printer-name—use lpmove

Printer-name is a printer that still has requests waiting to be printed. Use the lpmove command to move those requests to another printer.

scheduler is still running—can’t proceed

You cannot perform this command while the scheduler is running. Use the lpshut command first.

spool directory non-existent

The directory /var/spool has been removed. Use the mkdir command to restore the directory. This has probably removed some of the necessary lp files. You may have to reinstall the lp commands.

standard input is empty

You specified an invalid filename either by incorrectly typing a name or by specifying a nonexistent file. Nothing will be printed from this request.

this command for use only by lp Administrators

This command is restricted to someone logged in as root or lp.

too many options for interface program

The lp command called the appropriate interface program with too many arguments. For more information on the options and arguments that can be used with the lp command, refer to the lp(1)
reference page.


Tape Drive Error Indications

Following are some examples of commands and error messages. This is not an exhaustive list.

  • tar tvf /dev/nrtape

    tar: /dev/nrtape: No such device

  • cpio -itvI /dev/nrtape

    cpio: ERROR: Cannot open </dev/nrtape> for input. No such device

  • tar t

    tar: archive file /dev/tape does not exist or is a regular file

  • /usr/etc/restore t

    /dev/tape: No such file or directory

Enviado em Referencia, hp-ux | Deixar um comentário »

How to detect a memory leak in Microsoft Windows

Publicado por agostinhojr em 27 Abril, 2007

The term memory leak refers to the gradual loss of available computer memory when a bug causes a program (an application or part of Windows) to repeatedly fail to return the memory it has obtained for temporary use. As a result, the available memory for that application or that part of Windows becomes exhausted and the program can no longer function.
Applications with memory leaks or applications that consume excessive amounts of processor time can not only kill server performance, but can also render that server unstable.

In this technical guide, contributor Brien M. Posey provides you with the knowhow to determine if there is a memory leak in your Windows system.

Memory leaks: Finding a memory leak in Microsoft Windows

Before investing in server hardware, most companies spend a good deal of time researching the resources required to run the applications that the server will be hosting. But all this hard work can be undone by a poorly written application.

Over time, some applications can rob your server of resources far beyond any reasonable estimates. Applications with
memory leaks or applications that consume excessive amounts of processor time can not only kill server performance, but can also render that server unstable.
Memory issues with applicationsApplications usually request memory from the OS in order to perform various functions. Under normal circumstances, an application will release memory once it has finished using it. A leaky application will request memory like any other application, but will not release the memory that is no longer needed.


The next time that the application runs the function that required the additional memory, the application will not use the memory that it is already consuming. In fact, it will request even more memory from the OS. The leaky app continues to hold onto this memory even after it is no longer needed. Over time the leaky app will drain the OS of more and more memory.
Memory leaks are not always obvious. There is no dialog box in Microsoft Windows that says, “You have a memory leak.” It’s up to you to find memory leaks, and corrrect them. But how do you know if you’ve got one?


Symptoms of memory leaks The symptoms of a memory leak vary. They depend on the amount of memory the leaky app consumes each time the leaky code is executed, as well as how often the leaky code is executed. The frequency with which the system is rebooted also makes a difference, since memory is restored to the OS during a reboot.


Some memory leaks are barely noticeable. But if one becomes significant enough to start affecting the OS, you’ll see some telltale signs. Including:
The system gradually becomes slower. Sure, it’s normal for a system to slow down over time to some extent, due to disk fragmentation, the installation of bloated applications and the overhead associated with an increasing workload. What isn’t normal is for a system’s speed to be restored after a reboot, only to quickly begin slowing down again. This is often a sign of a memory leak (although it can also mean a malware infection).


Unexpected error messages indicating that various system services have stopped. Note: Again, these types of messages might be caused by malware infections or other types of system problems. If system services are shutting down unexpectedly, it is generally not a sign of a memory leak unless other symptoms are also occurring.
An error message indicating that Windows is either low on, or has run out of, virtual memory. Below is a typical sample of this type of error message, but the exact messsage will vary, depending upon the version of Windows your server is running.

Finding memory leaks using Performance Monitor

If your server is currently experiencing symptoms of a memory leak, you may be wondering how you can distinguish a memory leak from other types of performance problems.
There is no obvious message displayed indicating that a server is running a leaky application. Locating a memory leak usually involves watching various Performance Monitor counters and interpreting the results.

In the real world, it can be hard to tell if an application “leaks” unless you have something to compare it to. Fortunately, a Microsoft utility called Leakyapp does one thing: Creates a memory leak. This tool can help you observe how Performance Monitor behaves in memory leak situations.

Note: The Leakyapp utility causes a fairly serious memory leak to occur. Therefore, Performance Monitor data collected in the real world may not always be as dramatic as what you would observe using Leakyapp. When you look for memory leaks on production systems using Performance Monitor, the signs of a memory leak can be subtle.

If you want to learn how Leakyapp works, try this Leakyapp download, which consists of a 5.12 KB ZIP file.
Using Performance MonitorAccess Performance Monitor by entering the PERFMON command at the server’s Run prompt. When Performance Monitor opens, several counters (mechanisms that Performance Monitor uses to measure some individual aspect of the server’s performance) will already have been loaded. Click the X icon repeatedly until all default counters have been removed. You can now load new counters by clicking the + icon.

Individual counters are organized into performance objects, which are simply categories under which Performance Monitor counters are stored. From hereon, I will refer to individual counters in performance object/counter format. For example, Processor/% Processor Time refers to the % Processor Time counter found in the Processor performance object.

To detect a memory leak using Performance Monitor, monitor these counters:

  • The Memory/Available Bytes counter lets you view the total number of bytes of available memory. This value normally fluctuates, but if you have an application with the memory leak, it will decrease over time.
  • TheMemory/Committed Bytes counter will steadily rise if a memory leak is occurring, because as the number of available bytes of memory decreases, the number of committed bytes increases.
  • The Process/Private Bytes counter displays the number of bytes reserved exclusively for a specific process. If a memory leak is occurring, this value will tend to steadily rise.
  • The Process/Page File Bytes counter displays the size of the pagefile. Windows uses virtual memory (the pagefile) to supplement a machine’s physical memory. As a machine’s physical memory begins to fill up, pages of memory are moved to the pagefile. It is normal for the pagefile to be used even on machines with plenty of memory. But if the size of the pagefile steadily increases, that’s a good sign a memory leak is occurring.
  • I also want to mention the Process/Handle Count counter. Applications use handles to identify resources that they must access. If a memory leak is occurring, an application will often create additional handles to identify memory resources. So a rise in the handle count might indicate a memory leak. However, not all memory leaks will result in a rise in the handle count.


Memory leaks: Determine an application’s CPU consumption

One of the most common symptoms of a memory leak is that as time goes on, the computer runs slower and slower. Its speed is restored with a reboot, but it soons begin degrading again.
However, a memory leak is not the only condition that can cause these symptoms. They can also be caused by malware or by a poorly written application that consumes an excessive amount of CPU time. How can you tell how much CPU time an application is consuming, and whether that CPU consumption is a problem?

Determining application CPU usageDetermining how much CPU time an individual application is using is simple. Just press CTRL+ALT+Delete, then click the Task Manager button. When Task Manager opens, the Applications tab will display a list of all the applications running on the server.

Windows won’t actually display the amount of CPU time that an individual application is using. This is because Windows looks at the amount of system resources consumed by a process rather than an application. An application is made up of one or more processes. To see how much CPU time a process is using, select the Process tab.

The bottom of the screen below shows the total number of processes running on the machine at the given moment, along with the total percentage of CPU resources in use. The main part of the screen displays each individual process along with the percentage of CPU time the process is currently consuming. This screen displays both system processes and processes related to user-mode applications. The last process listed is the System Idle Process, which isn’t a process at all; it refers to how much of the CPU’s processing power is going unused at the current moment.

Any one of these processes (with the possible exception of the System Idle process) can momentarily consume all of the system’s processing power (100% CPU utilization). However, this does not necessarily indicate a problem. The only way to really find out whether a process is consuming an excessive amount of CPU time is to watch the process over time, and look at the average amount of CPU time it’s using.

Tracking CPU usage across systems

Windows’ Performance Monitor is not designed to track the CPU usage of individual processes, but it can track CPU usage across the entire system. The Processor\%ProcessorTime counter displays the current CPU usage similar to the way Task Manager does. The difference? This counter allows you to view average CPU consumption in addition to current CPU consumption.

If average CPU consumption is consistently above 80%, that’s usually a problem.
If average CPU consumption is consistently above 80%, that’s usually a problem. But looking at average CPU utilization isn’t enough. To determine if a process is having a detrimental effect on the CPU, you must know how the CPU is being used.

In some cases high processor utilization means that your system is struggling to keep up. In other situations, the CPU might have a high utilization value, but is actually working very efficiently. In these situations, a high utilization value is often caused by an access number of interrupts. Interrupts occur when drivers or operating system subcomponents need to access other hardware components, such as the hard disk.

Performance Monitor counters

There are several CPU-related Performance Monitor counters that you can watch to get a better idea of what’s going on with your server’s CPU. The System/Processor Queue Length counter displays the number of items that are waiting for the CPU to become available. If this queue regularly exceeds two items, the CPU is not performing adequately.

As I mentioned earlier, interrupts caused by hardware devices that need to access the CPU. The Processor/Interrupts/Second counter allows you to watch how many processor interrupts occur each second. The number of interrupts per second that are considered normal varies from server to server.

But if a hardware device is getting ready to fail, it will often generate an excessive number of interrupts. If the number of processor interrupts per second seems high compared to your other servers, and there does not appear to be enough activity to justify the spike it interrupts (such as disk access), it could be a sign that a hardware component is failing.
The Processor/% Interrupt Time counter shows you what percentage of time the CPU spends servicing hardware interrupts. Again, watch for spikes in an interrupt activity without a corresponding increase in system activity.

Of course our goal is to determine whether the amount of CPU time spent on a particular process is healthy. The Processor/% User Time counter shows the percentage of time the processor spends on user mode applications. Note: This counter only looks at non-idle CPU time. If this value is consistently high, it doesn’t necesarily mean your CPU is being overworked; it simply indicates that a disproportionate amount of the CPU’s resources are being spent on user mode processes as opposed to kernel mode processes or interrupts.

The Processor/% Privileged Time counter shows the percentage of non-idle CPU time being spent on kernel mode processes. If this value is disproportionately high, it either means that the user mode applications running on your server are not consuming much CPU resources, or that excessive interrupts are occurring and that a hardware component might be getting ready to fail.

Improving the CPU’s performance

It’s okay for an application to have disproportionately high CPU utilization so long as the system’s CPU utilization as a whole is not consistently above 80%. If that’s the case, you need to find out why. If you determine that the excessive CPU usage is related to the applications running on the server, it may be necessary to either upgrade the processor or to move some applications to a different server. Another option is to use processor affinity to assign each application to a specific processor.

Note: Applications with memory leaks can cause the CPU to work excessively. As a system’s available RAM decreases, the system relies increasingly on the pagefile. The more heavily the pagefile is used, the more time is spent swapping pages between physical and virtual memory.

This page-swapping process consumes both CPU time and disk time (which also consumes CPU time in the form of interrupts). If your system seems to the paging excessively, look for applications with memory leaks and correct them. If no memory leaks exist, try increasing the amount of RAM installed in the server. Doing so will often improve the CPU’s performance.

Artigo original

Enviado em Memory | Deixar um comentário »

Tabelas/Views SAP 4.0B

Publicado por agostinhojr em 26 Abril, 2007

Tabelas e Views que possuem informações relevantes para equipes de basis

DD03VT – Table fields – ABAP/4 Repository Information System

Enviado em SAP | Deixar um comentário »

PROCEDIMENTOS PARA GERENCIAR O LVM

Publicado por agostinhojr em 13 Abril, 2007

Quando voce instala a maquina ja e possivel definir o numero de filesystems desejados e o tamanho de cada um. Porem, com o passar do tempo, dependendo dos recursos de disco consumidos pela sua aplicacao, ou devido a compra de discos adicionais, torna-se necessario alterar a configuracao inicial: ou voce aumenta o tamanho de um filesystem, ou o diminui, ou cria novos filesystems.

Vamos reforcar alguns conceitos de uma forma bem simples antes de prosseguirmos com os exemplos:

VG == Volume Group: e o grupo de volumes de disco configurados na maquina. Em cada VG voce pode incluir 1 ou mais discos.

LVOL == Logical Volume: e a particao do disco. Quando voce criar o disco em um VG, deve particiona-lo (em 1 ou mais “pedacos”).

File System: depois de particionado o disco, voce podera criar um
sistema de arquivos para montar em um diretorio.

OBS.: Se voce precisar usar um “raw device”, basta criar
o VG e o LVOL (nao precisa criar o filesystem).

Queremos tambem ressaltar algumas observacoes importantes:

- O barra (/), onde esta o “/dev/vg00/lvol1″, nao pode ser
modificado, ou seja, nao e possivel aumentar e nem diminuir o seu
tamanho. Para altera-lo, e necessario uma reinstalacao do Sistema
Operacional.

- Voce pode alterar os volumes, atraves do SAM ou manualmente, com
excecao do /usr (se estiver em um volume logico separado do “/”), o
qual deve ser alterado apenas manualmente.

- Para alterar os volumes logicos (lvols), eles devem estar
desmontados.

- Nunca deixe de fazer backup regularmente e principalmente antes de
qualquer alteracao na configuracao do LVM.

A seguir listamos 8 exemplos de duvidas que ocorrem com mais
frequencia:

A – Como criar um novo VG;
B – Como remover um VG;
C – Como incluir um disco novo em um VG ja existente;
D – Como excluir um disco de um VG;
E – Como criar um novo LVOL;
F – Como remover um LVOL;
G – Como aumentar o tamanho de um LVOL;
H – Como diminuir o tamanho de um LVOL.

A – ) COMO CRIAR UM NOVO VG:

Nesse exemplo supomos que voce tinha apenas 1 disco configurado na
maquina e agora vai criar um novo VG para o segundo disco (um disco
novo):

1) Execute o comando “ioscan” para saber o endereco do disco:

# /usr/sbin/ioscan -fC disk

Class I H/W Path Driver S/W State H/W Type Description
================================================================
disk 1 52.5.0 disc3 CLAIMED DEVICE HP C2474S
disk 0 52.6.0 disc3 CLAIMED DEVICE HP C2247M1

Observe que temos um disco no endereco 6 e outro no endereco 5.

2) Verifique qual dos dois esta alocado no(s) VG(s) existente(s):

# /sbin/vgdisplay -v | grep “PV Name”
PV Name /dev/dsk/c0t6d0

Observe que realmente so temos um disco alocado em VG. Note que
esse disco e o dispositivo “c0t6d0″, o qual esta no endereco 6.
O disco de endereco 5 e o de dispositivo “c0t5d0″.

3) Crie um novo VG para o novo disco:

# mkdir /dev/vg01
# mknod /dev/vg01/group c 64 0×010000
|_> esse valor nao pode ser repetido
# /sbin/pvcreate /dev/rdsk/c0t5d0
# /sbin/vgcreate /dev/vg01 /dev/dsk/c0t5d0

B – ) COMO REMOVER UM VG:

Assumimos nesse exemplo que voce tem dois discos no VG01 e esse VG
tem dois LVOLs criados:

1) Devemos, em primeiro lugar, desmontar os filesystems do VG em
questao:

# /usr/sbin/umount /dev/vg01/lvol1
# /usr/sbin/umount /dev/vg01/lvol2

2) Agora, vamos remover os LVOLs criados para ele:

# /sbin/lvremove -f /dev/vg01/lvol1 /dev/vg01/lvol2

3) Em seguida, descobrimos quais discos fazem parte do VG01, para
removermos:

# /sbin/vgdisplay -v vg01 | grep “PV Name”
PV Name /dev/dsk/c0t5d0
PV Name /dev/dsk/c0t4d0

4) Verificamos nesse exemplo que temos dois discos no VG01.
Devemos remover “quase todos os discos” do VG01 (somente
deixamos um):

# /sbin/vgreduce /dev/vg01 /dev/dsk/c0t4d0

5) Restando apenas um disco no VG, basta remove-lo:

# /sbin/vgremove /dev/vg01

C – ) COMO INCLUIR UM DISCO NOVO EM UM VG JA EXISTENTE:

Assumimos nesse exemplo que voce somente tem o VG00, com um disco.
Vamos incluir o novo disco nesse mesmo VG:

1) Execute o comando “ioscan” para saber o endereco do disco:

# /usr/sbin/ioscan -fC disk

Class I H/W Path Driver S/W State H/W Type Description
================================================================
disk 1 52.5.0 disc3 CLAIMED DEVICE HP C2474S
disk 0 52.6.0 disc3 CLAIMED DEVICE HP C2247M1

Observe que temos um disco no endereco 6 e outro no endereco 5.

2) Verifique qual dos dois esta alocado no(s) VG(s) ja
existente(s):

# /sbin/vgdisplay -v | grep “PV Name”
PV Name /dev/dsk/c0t6d0

Observe que realmente so temos um disco alocado em VG. Note que
esse disco e o dispositivo “c0t6d0″, o qual esta no endereco 6.
O disco de endereco 5 e o de dispositivo “c0t5d0″.

3) Agora e so inclui-lo no VG00:

# /sbin/pvcreate /dev/rdsk/c0t5d0
# /sbin/vgextend /dev/vg00 /dev/dsk/c0t5d0

D – ) COMO EXCLUIR UM DISCO DE UM VG:

Assumimos nesse exemplo que voce tem dois discos no VG01 e esse VG tem dois LVOLs criados. O disco a ser removido e o de endereco 4. Tome o seguinte cuidado: pode ser que um determinado LVOL esteja ocupando uma parte de cada disco. Nesse caso, esse LVOL e perdido.

1) Devemos, em primeiro lugar, desmontar os filesystems do VG em
questao:

# /usr/sbin/umount /dev/vg01/lvol1
# /usr/sbin/umount /dev/vg01/lvol2

2) E necessario descobrir quais LVOLs fazem parte do disco de
endereco 4:

# /sbin/lvdisplay -v /dev/vg01/lvol2 | pg
— Logical volumes —

— Distribution of logical volume —
PV Name LE on PV PE on PV
/dev/dsk/c0t5d0 12 12
/dev/dsk/c0t4d0 40 40
||
\\==========> essa e a informacao que nos interessa.
— Logical extends —

# /sbin/lvdisplay -v /dev/vg01/lvol1 | pg
— Logical volumes —

— Distribution of logical volume —
PV Name LE on PV PE on PV
/dev/dsk/c0t5d0 12 12
||
\\==========> essa e a informacao que nos interessa.
— Logical extends —

Observe que nos comandos acima conseguimos visualizar que o
LVOL2 ocupa dois discos e o LVOL1 ocupa apenas um. O LVOL que
esta ocupando o disco a ser removido e o LVOL2.

3) Agora vamos remover o LVOL que ocupa o disco em questao:

# /sbin/lvremove -f /dev/vg01/lvol2

4) Livre de LVOLs, basta remover o disco do VG:

# /sbin/vgreduce /dev/vg01 /dev/dsk/c0t4d0

E – ) COMO CRIAR UM NOVO LVOL:

Nao se esqueca que para criar um LVOL, o VG ja deve estar previamente criado. Nesse exemplo assumimos que o VG01 ja esta criado, ja possui o LVOL1 e agora queremos usar o restante de seu espaco para criar outro LVOL (lvol2).

1) Primeiro devemos descobrir se ha espaco desalocado no VG e
quanto de espaco ainda ha disponivel:

# /sbin/vgdisplay vg01 | grep Free
Free PE 25

Se o numero resultante desse comando for 0, significa que nao
sera possivel criar um novo LVOL.

2) Vamos criar um LVOL com 25 extensoes (que tem 4Mb cada uma). O
tamanho em bytes e de (25 * 4) == 100Mb.

# /sbin/lvcreate -l 25 vg01

OBS.: O novo lvol e um numero sequencial, a partir do ultimo
criado. Como so tinhamos o LVOL1, o proximo a ser criado e
o LVOL2.

3) Se voce for usar um Raw Device, ou alocar essa area para swap
fisico, nao deve criar o sistema de arquivos. Porem, se voce
quiser usar esse LVOL para um sistema de arquivos, para montar
em um diretorio, deve cria-lo da seguinte forma:

# /usr/sbin/newfs -F vxfs /dev/vg01/rlvol2

4) Para monta-lo, ja deve existir o diretorio destino (e vazio!):

# mkdir /mnt
# /usr/sbin/mount /dev/vg01/lvol2 /mnt

5) Para que o sistema de arquivos seja montado automaticamente
durante o boot e necessario inclui-lo no arquivo /etc/fstab:

# vi /etc/fstab

/dev/vg01/lvol2 /mnt vxfs delaylog 0 2

OBS.: Verifique no manual a sintaxe da fstab para conhecer
mais detalhes.

F – ) COMO REMOVER UM LVOL:

Assumimos nesse exemplo a remocao do LVOL2 que esta no VG01:

1) Desmonte o LVOL em questao:

# /usr/sbin/umount /dev/vg01/lvol2

2) Remova o LVOL:

# /sbin/lvremove -f /dev/vg01/lvol2

3) Nao se esqueca de remove-lo da tabela “/etc/fstab”, antes de
resetar a maquina.

G – ) COMO AUMENTAR O TAMANHO DE UM LVOL:

Assumimos nesse exemplo o aumento do tamanho do LVOL2, que esta no VG01. Atualmente ele tem 572Mb e incluiremos nesse LVOL mais 40Mb.

LEMBRETE: nao e possivel aumentar o barra (“/”), que esta no LVOL1 do
VG00!!!

1) Verifique se ha espaco disponivel no VG, a fim de inclui-lo no
LVOL em questao:

# /sbin/vgdisplay vg01 | grep Free
Free PE 25

Se o numero resultante desse comando for 0, significa que nao
sera possivel aumentar um LVOL.

Nesse caso temos 25 extensoes (de 4Mb cada uma), totalizando
entao 100Mb ainda disponiveis.

Como queremos apenas 40Mb, usamos 10 extensoes (40 / 4 = 10).

2) Desmonte o LVOL em questao:

# /usr/sbin/umount /dev/vg01/lvol2

3) Garanta que o LVOL esta realmente desmontado, atraves do comando
“mount”: nao deve aparecer a linha desse LVOL.

4) Vamos agora descobrir quantas extensoes de 4Mb temos alocadas
atualmente no LVOL:

# /sbin/lvdisplay -v /dev/vg01/lvol2 | grep Current
Current LE 143

5) Totalizamos agora o novo numero de extensoes logicas:

143 + 10 = 153
| | |
| | |——-> total de extensoes (=> 153 * 4 = 612Mb).
| |————-> total que temos intencao de adicionar
| (=> 10 * 4 = 40Mb)
|——————> total de extensoes atualmente
(=> 143 * 4 = 572Mb)

Dessa forma chegamos a um novo tamanho de 612Mb.

6) Vamos agora aumentar o tamanho do LVOL:

# /sbin/lvextend -l 153 /dev/vg01/lvol2

7) Depois de aumentado o tamanho do LVOL, precisamos aumentar o
tamanho do sistema de arquivos para compatibilizar os tamanhos:

# /usr/sbin/extendfs –F vxfs /dev/vg01/rlvol2

8) Por ultimo, e so montar novamente o LVOL e usa-lo ja com o novo
tamanho!

H – ) COMO DIMINUIR O TAMANHO DE UM LVOL:

Assumimos nesse exemplo a diminuicao do LVOL2 que esta no VG01. Hoje, o LVOL2 esta com 612Mb e queremos deixa-lo com apenas 500Mb.

LEMBRETE: nao e possivel diminuir o tamanho do barra (“/”), que esta
no LVOL1 do VG00!!!

1) Em primeiro lugar devemos fazer um backup do diretorio onde esta
montado o LVOL2, pois ao diminuirmos o seu tamanho, perderemos
os dados:

# cd /diretorio
# find . -print | cpio -ocvB > /dev/rmt/c0t0d0BEST

2) Em seguida, desmontamos o LVOL:

# cd / ; umount /dev/vg01/lvol2

3) Garanta que o LVOL esta realmente desmontado, atraves do comando
“mount”: nao deve aparecer a linha desse LVOL.

4) Como o LVOL esta com 612Mb e queremos diminui-lo para 500Mb,
devemos calcular o numero de extensoes contidas em 500Mb:

calcule: 500 / 4 = 125

5) Reduza agora o tamanho do LVOL:

# /sbin/lvreduce -l 125 /dev/vg01/lvol2

6) Crie um novo sistema de arquivos (pois nao e possivel apenas
diminuir o tamanho do sistema de arquivos):

# /usr/sbin/newfs -F vxfs /dev/vg01/rlvol2

7) Monte o filesystem e restaure os dados do backup:

# mount /dev/vg01/lvol2 /diretorio
# cd /diretorio
# cpio -icvdumB < /dev/rmt/c0t0d0BEST

GERENCIAMENTO DO LVOL COM ADVANCED JFS

1. Como aumentar o tamanho do lvol:

Atencao: Para os procedimentos abaixo E’ necessario que o pacote HP OnLine JFS Advanced VxFS esteja instalado.

1.1 – Verifique se existe espaco disponivel no vg00:

# /sbin/vgdisplay -v vg00 |grep Free
Free PE 178

Se o numero mostrado for 0, indica que o seu vg nao tem espaco
disponivel para criar um novo lvol.

Atencao: Note que no item anterior, nos desmontamos o lvol; nesse
caso, com o pacote instalado, nao E’ necessario.

1.2 – Como queremos aumentar o lvol para o tamanho de 140MB, podemos
utilizar:

# /sbin/lvextend -L 140 /dev/vg00/lvol10
Logical volume “/dev/vg00/lvol10″ has been successfully extended. Volume Group configuration for /dev/vg00 has been saved in /etc/lvmconf/vg00.conf

1.3 – Aumente o tamanho do sistema de arquivos para compatibilizar o
tamanho:

# /usr/sbin/fsadm -F vxfs -b 143360 /teste
fsadm: /dev/vg00/rlvol10 is currently 102400 sectors – size will be increased

onde:
-b (total lvol * 1024)

1.4 – Para confirmar que o lvol foi realmente aumentado, pode-se executar:

#/usr/bin/bdf
ou
#/usr/sbin/lvdisplay /dev/vg00/lvol10

2. Reduzindo o tamanho do lvol

2.1 – Tire backup do lvol (por seguranca).
2.2 – Nao E’ necessario desmontar o lvol.
2.3 – Reduzindo o lvol:

# /usr/sbin/fsadm -F vxfs -b 102400 /teste
fsadm: /dev/vg00/rlvol10 is currently 155648 sectors – size will be reduced

#/usr/sbin/lvreduce -L 100 /dev/vg00/lvol10
Then a logical volume is reduced useful data might get lost; do you really want the command to proceed (y/n) : y Logical volume “/dev/vg00/lvol10″ has been successfully reduced. Volume Group configuration for /dev/vg00 has been saved in /etc/lvmconf/vg00.conf

2.4 – Para confirmar que o lvol foi realmente aumentado, pode-se
executar:

#/usr/bin/bdf
ou
#/usr/sbin/lvdisplay -v /dev/vg00/lvol10

Enviado em hp-ux | Deixar um comentário »

Menu do Excel desaparece

Publicado por agostinhojr em 26 Março, 2007

Ao abrir o meu excel tive um problema que foi o desaparecimento do menu do excel. Para resolver o problema tive que executar os seguintes paços:

  • Abrir o Excel.
  • Pressionar ALT + F11 para ativar o Editor do Visual Basic.
  • Abra uma janela dando um clique duplo no nome da planilha e execute o codigo abaixo.
  • Depois clique com o botão direito sobre a barra do menu e selecione personalizar.
  • Selecione a aba Barra de ferramentas e selecionar novamente todas as barras que sumiram.

Codigo para execução no VB

Sub ResetMenu()
Application.CommandBars(1).Enabled = True
End Sub

Enviado em office | 1 Comentário »

Como buscar uma string nos steps de jobs (MS SQL)

Publicado por agostinhojr em 23 Março, 2007

Utilize SQL abaixo para listar todos os jobs que possuem uma string, substituindo a palavra BUSCA pela string que deseja localizar.

SELECT j.name
FROM msdb.dbo.sysjobsteps js
inner join msdb.dbo.sysjobs j on j.job_id = js.job_id
WHERE (command LIKE ‘%BUSCA%’)

Enviado em MS SQL | Deixar um comentário »

Regular Expressions

Publicado por agostinhojr em 21 Março, 2007


NAME

perlre – Perl regular expressions

DESCRIPTION

This page describes the syntax of regular expressions in Perl. For a description of how to use regular expressions in matching operations, plus various examples of the same, see discussions of m//, s///, qr// and ?? in perlop/”Regexp Quote-Like Operators”. Matching operations can have various modifiers. Modifiers that relate to the interpretation of the regular expression inside are listed below. Modifiers that alter the way a regular expression is used by Perl are detailed in perlop/”Regexp Quote-Like Operators” and perlop/”Gory details of parsing quoted constructs”.

i
Do case-insensitive pattern matching. If use locale is in effect, the case map is taken from the current locale. See perllocale.
m
Treat string as multiple lines. That is, change “^” and “$” from matching the start or end of the string to matching the start or end of any line anywhere within the string.
s
Treat string as single line. That is, change “.” to match any character whatsoever, even a newline, which normally it would not match. The /s and /m modifiers both override the $* setting. That is, no matter what $* contains, /s without /m will force “^” to match only at the beginning of the string and “$” to match only at the end (or just before a newline at the end) of the string. Together, as /ms, they let the “.” match any character whatsoever, while yet allowing “^” and “$” to match, respectively, just after and just before newlines within the string.
x
Extend your pattern’s legibility by permitting whitespace and comments.

These are usually written as “the /x modifier”, even though the delimiter in question might not really be a slash. Any of these modifiers may also be embedded within the regular expression itself using the (?…) construct. See below. The /x modifier itself needs a little more explanation. It tells the regular expression parser to ignore whitespace that is neither backslashed nor within a character class. You can use this to break up your regular expression into (slightly) more readable parts. The # character is also treated as a metacharacter introducing a comment, just as in ordinary Perl code. This also means that if you want real whitespace or # characters in the pattern (outside a character class, where they are unaffected by /x), that you’ll either have to escape them or encode them using octal or hex escapes. Taken together, these features go a long way towards making Perl’s regular expressions more readable. Note that you have to be careful not to include the pattern delimiter in the comment–perl has no way of knowing you did not intend to close the pattern early. See the C-comment deletion code in perlop.

Regular Expressions

The patterns used in Perl pattern matching derive from supplied in the Version 8 regex routines. (The routines are derived (distantly) from Henry Spencer’s freely redistributable reimplementation of the V8 routines.) See Version 8 Regular Expressions for details. In particular the following metacharacters have their standard egrep-ish meanings:

    \ Quote the next metacharacter    ^ Match the beginning of the line    . Match any character (except newline)    $ Match the end of the line (or before newline at the end)     Alternation    () Grouping    [] Character class  

By default, the “^” character is guaranteed to match only the beginning of the string, the “$” character only the end (or before the newline at the end), and Perl does certain optimizations with the assumption that the string contains only one line. Embedded newlines will not be matched by “^” or “$”. You may, however, wish to treat a string as a multi-line buffer, such that the “^” will match after any newline within the string, and “$” will match before any newline. At the cost of a little more overhead, you can do this by using the /m modifier on the pattern match operator. (Older programs did this by setting $*, but this practice is now deprecated.) To simplify multi-line substitutions, the “.” character never matches a newline unless you use the /s modifier, which in effect tells Perl to pretend the string is a single line–even if it isn’t. The /s modifier also overrides the setting of $*, in case you have some (badly behaved) older code that sets it in another module. The following standard quantifiers are recognized:

    *    Match 0 or more times    +    Match 1 or more times    ?    Match 1 or 0 times    {n}    Match exactly n times    {n,}   Match at least n times    {n,m}  Match at least n but not more than m times  

(If a curly bracket occurs in any other context, it is treated as a regular character.) The “*” modifier is equivalent to {0,}, the “+” modifier to {1,}, and the “?” modifier to {0,1}. n and m are limited to integral ( answerid, faqid, answer, uid, status, datesub) values less than a preset limit defined when perl is built. This is usually 32766 on the most common platforms. The actual limit can be seen in the error message generated by code such as this:

    $_ **= $_ , / {$_} / for 2 .. 42;  

By default, a quantified subpattern is “greedy”, that is, it will match as many times as possible (given a particular starting location) while still allowing the rest of the pattern to match. If you want it to match the minimum number of times possible, follow the quantifier with a “?”. Note that the meanings don’t change, just the “greediness”:

    *?    Match 0 or more times    +?    Match 1 or more times    ??    Match 0 or 1 time    {n}?   Match exactly n times    {n,}?  Match at least n times    {n,m}? Match at least n but not more than m times  

Because patterns are processed as double quoted strings, the following also work:

    \t  tab                   (HT, TAB)    \n  newline               (LF, NL)    \r  return                (CR)    \f  form feed             (FF)    \a  alarm (bell)          (BEL)    \e  escape (think troff)  (ESC)    33 octal char (think of a PDP-11)    \x1B hex char    \x{263a} wide hex char         (Unicode SMILEY)    \c[  control char    \N{name} named char    \l  lowercase next char (think vi)    \u  uppercase next char (think vi)    \L  lowercase till \E (think vi)    \U  uppercase till \E (think vi)    \E  end case modification (think vi)    \Q  quote (disable) pattern metacharacters till \E  

If use locale is in effect, the case map used by \l, \L, \u and \U is taken from the current locale. See perllocale. For documentation of \N{name}, see charnames. You cannot include a literal $ or @ within a \Q sequence. An unescaped $ or @ interpolates the corresponding variable, while escaping will cause the literal string \$ to be matched. You'll need to write something like m/\Quser\E\@\Qhost/. In addition, Perl defines the following:

    \w Match a "word" character (alphanumeric plus "_")    \W Match a non-word character    \s Match a whitespace character    \S Match a non-whitespace character    \d Match a digit character    \D Match a non-digit character    \pP Match P, named property.  Use \p{Prop} for longer names.    \PP Match non-P    \X Match eXtended Unicode "combining character sequence",        equivalent to Cmenorque(?:\PM\pM*)maiorque    \C Match a single C char (octet) even under utf8.  

A \w matches a single alphanumeric character, not a whole word. Use \w+ to match a string of Perl-identifier characters (which isn't the same as matching an English word). If use locale is in effect, the list of alphabetic characters generated by \w is taken from the current locale. See perllocale. You may use \w, \W, \s, \S, \d, and \D within character classes, but if you try to use them as endpoints of a range, that's not a range, the "-" is understood literally. See utf8 for details about \pP, \PP, and \X. The POSIX character class syntax

    [:class:]  

is also available. The available classes and their backslash equivalents (if available) are as follows:

    alpha    alnum    ascii    cntrl    digit       \d    graph    lower    print    punct    space       \s    upper    word        \w    xdigit  

For example use [:upper:] to match all the uppercase characters. Note that the [] are part of the [::] construct, not part of the whole character class. For example:

    [01[:alpha:]%]  

matches one, zero, any alphabetic character, and the percentage sign. If the utf8 pragma is used, the following equivalences to Unicode \p{} constructs hold:

    alpha       IsAlpha    alnum       IsAlnum    ascii       IsASCII    cntrl       IsCntrl    digit       IsDigit    graph       IsGraph    lower       IsLower    print       IsPrint    punct       IsPunct    space       IsSpace    upper       IsUpper    word        IsWord    xdigit      IsXDigit  

For example [:lower:] and \p{IsLower} are equivalent. If the utf8 pragma is not used but the locale pragma is, the classes correlate with the isalpha(3) interface (except for `word’, which is a Perl extension, mirroring \w). The assumedly non-obviously named classes are:

cntrl
Any control character. Usually characters that don’t produce output as such but instead control the terminal somehow: for example newline and backspace are control characters. All characters with ord() less than 32 are most often classified as control characters.
graph
Any alphanumeric or punctuation character.
print
Any alphanumeric or punctuation character or space.
punct
Any punctuation character.
xdigit
Any hexadecimal digit. Though this may feel silly (/0-9a-f/i would work just fine) it is included for completeness.

You can negate the [::] character classes by prefixing the class name with a ‘^’. This is a Perl extension. For example:

    POSIX trad. Perl  utf8 Perl

    [:^digit:]      \D      \P{IsDigit}    [:^space:]     \S     \P{IsSpace}    [:^word:]     \W     \P{IsWord}  

The POSIX character classes [.cc.] and [=cc=] are recognized but not supported and trying to use them will cause an error. Perl defines the following zero-width assertions:

    \b Match a word boundary    \B Match a non-(word boundary)    \A Match only at beginning of string    \Z Match only at end of string, or before newline at the end    \z Match only at end of string    \G Match only at pos() (e.g. at the end-of-match position        of prior m//g)  

A word boundary (\b) is a spot between two characters that has a \w on one side of it and a \W on the other side of it (in either order), counting the imaginary characters off the beginning and end of the string as matching a \W. (Within character classes \b represents backspace rather than a word boundary, just as it normally does in any double-quoted string.) The \A and \Z are just like “^” and “$”, except that they won’t match multiple times when the /m modifier is used, while “^” and “$” will match at every internal line boundary. To match the actual end of the string and not ignore an optional trailing newline, use \z. The \G assertion can be used to chain global matches (using m//g), as described in perlop/”Regexp Quote-Like Operators”. It is also useful when writing lex-like scanners, when you have several patterns that you want to match against consequent substrings of your string, see the previous reference. The actual location where \G will match can also be influenced by using pos() as an lvalue. See perlfunc/pos. The bracketing construct ( … ) creates capture buffers. To refer to the digit’th buffer use \menorquedigitmaiorque within the match. Outside the match use “$” instead of “\”. (The \menorquedigitmaiorque notation works in certain circumstances outside the match. See the warning below about \1 vs $1 for details.) Referring back to another part of the match is called a backreference. There is no limit to the number of captured substrings that you may use. However Perl also uses \10, \11, etc. as aliases for 10, 11, etc. (Recall that 0 means octal, so 11 is the 9′th ASCII character, a tab.) Perl resolves this ambiguity by interpreting \10 as a backreference only if at least 10 left parentheses have opened before it. Likewise \11 is a backreference only if at least 11 left parentheses have opened before it. And so on. \1 through \9 are always interpreted as backreferences.” Examples:

    s/^([^ ]*) *([^ ]*)/$2 $1/;     # swap first two words

     if (/(.)\1/) {                 # find first doubled char         print "'$1' is the first doubled character\n";     }

    if (/Time: (..):(..):(..)/) {   # parse out ( answerid, faqid, answer, uid, status, datesub) values $hours = $1; $minutes = $2; $seconds = $3;    }  

Several special variables also refer back to portions of the previous match. $+ returns whatever the last bracket match matched. $& returns the entire matched string. (At one point $0 did also, but now it returns the name of the program.) $` returns everything before the matched string. And $’ returns everything after the matched string. The numbered variables ($1, $2, $3, etc.) and the related punctuation set (menorque$+, $&, $`, and $’) are all dynamically scoped until the end of the enclosing block or until the next successful match, whichever comes first. (See perlsyn/”Compound Statements”.) WARNING: Once Perl sees that you need one of $&, $`, or $’ anywhere in the program, it has to provide them for every pattern match. This may substantially slow your program. Perl uses the same mechanism to produce $1, $2, etc, so you also pay a price for each pattern that contains capturing parentheses. (To avoid this cost while retaining the grouping behaviour, use the extended regular expression (?: … ) instead.) But if you never use $&, $` or $’, then patterns without capturing parentheses will not be penalized. So avoid $&, $’, and $` if you can, but if you can’t (and some algorithms really appreciate them), once you’ve used them once, use them at will, because you’ve already paid the price. As of 5.005, $& is not so costly as the other two. Backslashed metacharacters in Perl are alphanumeric, such as \b, \w, \n. Unlike some other regular expression languages, there are no backslashed symbols that aren’t alphanumeric. So anything that looks like \\, \(, \), \menorque, \maiorque, \{, or \} is always interpreted as a literal character, not a metacharacter. This was once used in a common idiom to disable or quote the special meanings of regular expression metacharacters in a string that you want to use for a pattern. Simply quote all non-alphanumeric characters:

    $pattern =~ s/(\W)/\\$1/g;  

Today it is more common to use the quotemeta() function or the \Q metaquoting escape sequence to disable all metacharacters’ special meanings like this:

    /$unquoted\Q$quoted\E$unquoted/  

Beware that if you put literal backslashes (those not inside interpolated variables) between \Q and \E, double-quotish backslash interpolation may lead to confusing results. If you need to use literal backslashes within \Q…\E, consult perlop/”Gory details of parsing quoted constructs”.

Extended Patterns

Perl also defines a consistent extension syntax for features not found in standard tools like awk and lex. The syntax is a pair of parentheses with a question mark as the first thing within the parentheses. The character after the question mark indicates the extension. The stability of these extensions varies widely. Some have been part of the core language for many years. Others are experimental and may change without warning or be completely removed. Check the documentation on an individual feature to verify its current status. A question mark was chosen for this and for the minimal-matching construct because 1) question marks are rare in older regular expressions, and 2) whenever you see one, you should stop and “question” exactly what is going on. That’s psychology…

(?#text)
A comment. The text is ignored. If the /x modifier enables whitespace formatting, a simple # will suffice. Note that Perl closes the comment as soon as it sees a ), so there is no way to put a literal ) in the comment.
(?imsx-imsx)
One or more embedded pattern-match modifiers. This is particularly useful for dynamic patterns, such as those read in from a configuration file, read in as an argument, are specified in a table somewhere, etc. Consider the case that some of which want to be case sensitive and some do not. The case insensitive ones need to include merely (?i) at the front of the pattern. For example:
    $pattern = "foobar";    if ( /$pattern/i ) { }

    # more flexible:

    $pattern = "(?i)foobar";    if ( /$pattern/ ) { }   

Letters after a - turn those modifiers off. These modifiers are localized inside an enclosing group (if any). For example,

    ( (?i) blah ) \s+ \1  

will match a repeated (including the case!) word blah in any case, assuming x modifier, and no i modifier outside this group.

(?:pattern)
(?imsx-imsx:pattern)
This is for clustering, not capturing; it groups subexpressions like “()”, but doesn’t make backreferences as “()” does. So
    @fields = split(/\b(?:abc)\b/)  

is like

    @fields = split(/\b(abc)\b/)  

but doesn’t spit out extra fields. It’s also cheaper not to capture characters if you don’t need to. Any letters between ? and : act as flags modifiers as with (?imsx-imsx). For example,

    /(?s-i:more.*than).*million/i  

is equivalent to the more verbose

    /(?:(?s-i)more.*than).*million/i  

(?=pattern)
A zero-width positive look-ahead assertion. For example, /\w+(?=\t)/ matches a word followed by a tab, without including the tab in $&.
(?!pattern)
A zero-width negative look-ahead assertion. For example /foo(?!bar)/ matches any occurrence of “foo” that isn’t followed by “bar”. Note however that look-ahead and look-behind are NOT the same thing. You cannot use this for look-behind. If you are looking for a “bar” that isn’t preceded by a “foo”, /(?!foo)bar/ will not do what you want. That’s because the (?!foo) is just saying that the next thing cannot be “foo”–and it’s not, it’s a “bar”, so “foobar” will match. You would have to do something like /(?!foo)…bar/ for that. We say “like” because there’s the case of your “bar” not having three characters before it. You could cover that this way: /(?:(?!foo)…^.{0,2})bar/. Sometimes it’s still easier just to say:
    if (/bar/ &amp;& $` !~ /foo$/)  

For look-behind see below.

(?menorque=pattern)
A zero-width positive look-behind assertion. For example, /(?menorque=\t)\w+/ matches a word that follows a tab, without including the tab in $&. Works only for fixed-width look-behind.
(?menorque!pattern)
A zero-width negative look-behind assertion. For example /(?menorque!bar)foo/ matches any occurrence of “foo” that does not follow “bar”. Works only for fixed-width look-behind.
(?{ code })
WARNING: This extended regular expression feature is considered highly experimental, and may be changed or deleted without notice. This zero-width assertion evaluate any embedded Perl code. It always succeeds, and its code is not interpolated. Currently, the rules to determine where the code ends are somewhat convoluted. The code is properly scoped in the following sense: If the assertion is backtracked (compare “Backtracking”), all changes introduced after localization are undone, so that
  $_ = 'a' x 8;  mmenorque     (?{ $cnt = 0 })   # Initialize $cnt.     (       a       (?{           local $cnt = $cnt + 1; # Update $cnt, backtracking-safe.       })     )*      aaaa     (?{ $res = $cnt })   # On success copy to non-localized     # location.   maiorquex;  

will set $res = 4. Note that after the match, $cnt returns to the globally introduced value, because the scopes that restrict local operators are unwound. This assertion may be used as a (?(condition)yes-patternno-pattern) switch. If not used in this way, the result of evaluation of code is put into the special variable $^R. This happens immediately, so $^R can be used from other (?{ code }) assertions inside the same regular expression. The assignment to $^R above is properly localized, so the old value of $^R is restored if the assertion is backtracked; compare “Backtracking”. For reasons of security, this construct is forbidden if the regular expression involves run-time interpolation of variables, unless the perilous use re ‘eval’ pragma has been used (see re), or the variables contain results of qr// operator (see perlop/”qr/STRING/imosx”). This restriction is because of the wide-spread and remarkably convenient custom of using run-time determined strings as patterns. For example:

    $re = menorquemaiorque;    chomp $re;    $string =~ /$re/;  

Before Perl knew how to execute interpolated code within a pattern, this operation was completely safe from a security point of view, although it could raise an exception from an illegal pattern. If you turn on the use re ‘eval’, though, it is no longer secure, so you should only do so if you are also using taint checking. Better yet, use the carefully constrained evaluation within a Safe module. See perlsec for details about both these mechanisms.

(??{ code })
WARNING: This extended regular expression feature is considered highly experimental, and may be changed or deleted without notice. A simplified version of the syntax may be introduced for commonly used idioms. This is a “postponed” regular subexpression. The code is evaluated at run time, at the moment this subexpression may match. The result of evaluation is considered as a regular expression and matched as if it were inserted instead of this construct. The code is not interpolated. As before, the rules to determine where the code ends are currently somewhat convoluted. The following pattern matches a parenthesized group:
  $re = qr{      \(      (?:  (?maiorque [^()]+ ) # Non-parens without backtracking

  (??{ $re }) # Group with matching parens      )*      \)   }x;  

(?maiorquepattern)
WARNING: This extended regular expression feature is considered highly experimental, and may be changed or deleted without notice. An “independent” subexpression, one which matches the substring that a standalonepattern would match if anchored at the given position, and it matches nothing other than this substring. This construct is useful for optimizations of what would otherwise be “eternal” matches, because it will not backtrack (see “Backtracking”). It may also be useful in places where the “grab all you can, and do not give anything back” semantic is desirable. For example: ^(?maiorquea*)ab will never match, since (?maiorquea*) (anchored at the beginning of string, as above) will match all characters a at the beginning of string, leaving no a for ab to match. In contrast, a*ab will match the same as a+b, since the match of the subgroup a* is influenced by the following group ab (see “Backtracking”). In particular, a* inside a*ab will match fewer characters than a standalone a*, since this makes the tail match. An effect similar to (?maiorquepattern) may be achieved by writing (?=(pattern))\1. This matches the same substring as a standalone a+, and the following \1 eats the matched string; it therefore makes a zero-length assertion into an analogue of (?maiorque…). (The difference between these two constructs is that the second one uses a capturing group, thus shifting ordinals of backreferences in the rest of a regular expression.) Consider this pattern:
    m{ \(   (     [^()]+  # x+

            \( [^()]* \)          )+       \)     }x  

That will efficiently match a nonempty group with matching parentheses two levels deep or less. However, if there is no such group, it will take virtually forever on a long string. That’s because there are so many different ways to split a long string into several substrings. This is what (.+)+ is doing, and (.+)+ is similar to a subpattern of the above pattern. Consider how the pattern above detects no-match on ((()aaaaaaaaaaaaaaaaaa in several seconds, but that each extra letter doubles this time. This exponential performance will make it appear that your program has hung. However, a tiny change to this pattern

    m{ \(   (     (?maiorque [^()]+ ) # change x+ above to (?maiorque x+ )

            \( [^()]* \)          )+       \)     }x  

which uses (?maiorque…) matches exactly when the one above does (verifying this yourself would be a productive exercise), but finishes in a fourth the time when used on a similar string with 1000000 as. Be aware, however, that this pattern currently triggers a warning message under the use warnings pragma or -w switch saying it “matches the null string many times”): On simple groups, such as the pattern (?maiorque [^()]+ ), a comparable effect may be achieved by negative look-ahead, as in [^()]+ (?! [^()] ). This was only 4 times slower on a string with 1000000 as. The “grab all you can, and do not give anything back” semantic is desirable in many situations where on the first sight a simple ()* looks like the correct solution. Suppose we parse text with comments being delimited by # followed by some optional (horizontal) whitespace. Contrary to its appearence, #[ \t]*is not the correct subexpression to match the comment delimiter, because it may “give up” some whitespace if the remainder of the pattern can be made to match that way. The correct answer is either one of these:

    (?maiorque#[ \t]*)    #[ \t]*(?![ \t])  

For example, to grab non-empty comments into $1, one should use either one of these:

    / (?maiorque \# [ \t]* ) (        .+ ) /x;    /     \# [ \t]*   ( [^ \t] .* ) /x;  

Which one you pick depends on which of these expressions better reflects the above specification of comments.

(?(condition)yes-patternno-pattern)
(?(condition)yes-pattern)
WARNING: This extended regular expression feature is considered highly experimental, and may be changed or deleted without notice. Conditional expression. (condition) should be either an integer in parentheses (which is valid if the corresponding pair of parentheses matched), or look-ahead/look-behind/evaluate zero-width assertion. For example:
    m{ ( \( )?       [^()]+       (?(1) \) )     }x  

matches a chunk of non-parentheses, possibly included in parentheses themselves.

Backtracking

NOTE: This section presents an abstract approximation of regular expression behavior. For a more rigorous (and complicated) view of the rules involved in selecting a match among possible alternatives, see Combining pieces together. A fundamental feature of regular expression matching involves the notion called backtracking, which is currently used (when needed) by all regular expression quantifiers, namely *, *?, +, +?, {n,m}, and {n,m}?. Backtracking is often optimized internally, but the general principle outlined here is valid. For a regular expression to match, the entire regular expression must match, not just part of it. So if the beginning of a pattern containing a quantifier succeeds in a way that causes later parts in the pattern to fail, the matching engine backs up and recalculates the beginning part–that’s why it’s called backtracking. Here is an example of backtracking: Let’s say you want to find the word following “foo” in the string “Food is on the foo table.”:

    $_ = "Food is on the foo table.";    if ( /\b(foo)\s+(\w+)/i ) { print "$2 follows $1.\n";    }  

When the match runs, the first part of the regular expression (\b(foo)) finds a possible match right at the beginning of the string, and loads up $1 with “Foo”. However, as soon as the matching engine sees that there’s no whitespace following the “Foo” that it had saved in $1, it realizes its mistake and starts over again one character after where it had the tentative match. This time it goes all the way until the next occurrence of “foo”. The complete regular expression matches this time, and you get the expected output of “table follows foo.” Sometimes minimal matching can help a lot. Imagine you’d like to match everything between “foo” and “bar”. Initially, you write something like this:

    $_ =  "The food is under the bar in the barn.";    if ( /foo(.*)bar/ ) { print "got menorque$1maiorque\n";    }  

Which perhaps unexpectedly yields:

  got menorqued is under the bar in the maiorque  

That’s because .* was greedy, so you get everything between the first “foo” and the last “bar”. Here it’s more effective to use minimal matching to make sure you get the text between a “foo” and the first “bar” thereafter.

    if ( /foo(.*?)bar/ ) { print "got menorque$1maiorque\n" }  got menorqued is under the maiorque  

Here’s another example: let’s say you’d like to match a number at the end of a string, and you also want to keep the preceding part the match. So you write this:

    $_ = "I have 2 numbers: 53147";    if ( /(.*)(\d*)/ ) {    # Wrong! print "Beginning is menorque$1maiorque, number is menorque$2maiorque.\n";    }  

That won’t work at all, because .* was greedy and gobbled up the whole string. As \d* can match on an empty string the complete regular expression matched successfully.

    Beginning is menorqueI have 2 numbers: 53147maiorque, number is menorquemaiorque.  

Here are some variants, most of which don’t work:

    $_ = "I have 2 numbers: 53147";    @pats = qw{ (.*)(\d*) (.*)(\d+) (.*?)(\d*) (.*?)(\d+) (.*)(\d+)$ (.*?)(\d+)$ (.*)\b(\d+)$ (.*\D)(\d+)$    };

    for $pat (@pats) { printf "%-12s ", $pat; if ( /$pat/ ) {     print "menorque$1maiorque menorque$2maiorque\n"; } else {     print "FAIL\n"; }    }  

That will print out:

    (.*)(\d*)    menorqueI have 2 numbers: 53147maiorque menorquemaiorque    (.*)(\d+)    menorqueI have 2 numbers: 5314maiorque menorque7maiorque    (.*?)(\d*)   menorquemaiorque menorquemaiorque    (.*?)(\d+)   menorqueI have maiorque menorque2maiorque    (.*)(\d+)$   menorqueI have 2 numbers: 5314maiorque menorque7maiorque    (.*?)(\d+)$  menorqueI have 2 numbers: maiorque menorque53147maiorque    (.*)\b(\d+)$ menorqueI have 2 numbers: maiorque menorque53147maiorque    (.*\D)(\d+)$ menorqueI have 2 numbers: maiorque menorque53147maiorque  

As you see, this can be a bit tricky. It’s important to realize that a regular expression is merely a set of assertions that gives a definition of success. There may be 0, 1, or several different ways that the definition might succeed against a particular string. And if there are multiple ways it might succeed, you need to understand backtracking to know which variety of success you will achieve. When using look-ahead assertions and negations, this can all get even tricker. Imagine you’d like to find a sequence of non-digits not followed by “123″. You might try to write that as

    $_ = "ABC123";    if ( /^\D*(?!123)/ ) {  # Wrong! print "Yup, no 123 in $_\n";    }  

But that isn’t going to match; at least, not the way you’re hoping. It claims that there is no 123 in the string. Here’s a clearer picture of why it that pattern matches, contrary to popular expectations:

    $x = 'ABC123' ;    $y = 'ABC445' ;

    print "1: got $1\n" if $x =~ /^(ABC)(?!123)/ ;    print "2: got $1\n" if $y =~ /^(ABC)(?!123)/ ;

    print "3: got $1\n" if $x =~ /^(\D*)(?!123)/ ;    print "4: got $1\n" if $y =~ /^(\D*)(?!123)/ ;  

This prints

    2: got ABC    3: got AB    4: got ABC  

You might have expected test 3 to fail because it seems to a more general purpose version of test 1. The important difference between them is that test 3 contains a quantifier (\D*) and so can use backtracking, whereas test 1 will not. What’s happening is that you’ve asked “Is it true that at the start of $x, following 0 or more non-digits, you have something that’s not 123?” If the pattern matcher had let \D* expand to “ABC”, this would have caused the whole pattern to fail. The search engine will initially match \D* with “ABC”. Then it will try to match (?!123 with “123″, which fails. But because a quantifier (\D*) has been used in the regular expression, the search engine can backtrack and retry the match differently in the hope of matching the complete regular expression. The pattern really, really wants to succeed, so it uses the standard pattern back-off-and-retry and lets \D* expand to just “AB” this time. Now there’s indeed something following “AB” that is not “123″. It’s “C123″, which suffices. We can deal with this by using both an assertion and a negation. We’ll say that the first part in $1 must be followed both by a digit and by something that’s not “123″. Remember that the look-aheads are zero-width expressions–they only look, but don’t consume any of the string in their match. So rewriting this way produces what you’d expect; that is, case 5 will fail, but case 6 succeeds:

    print "5: got $1\n" if $x =~ /^(\D*)(?=\d)(?!123)/ ;    print "6: got $1\n" if $y =~ /^(\D*)(?=\d)(?!123)/ ;

    6: got ABC  

In other words, the two zero-width assertions next to each other work as though they’re ANDed together, just as you’d use any built-in assertions: /^$/ matches only if you’re at the beginning of the line AND the end of the line simultaneously. The deeper underlying truth is that juxtaposition in regular expressions always means AND, except when you write an explicit OR using the vertical bar. /ab/ means match “a” AND (then) match “b”, although the attempted matches are made at different positions because “a” is not a zero-width assertion, but a one-width assertion. WARNING: particularly complicated regular expressions can take exponential time to solve because of the immense number of possible ways they can use backtracking to try match. For example, without internal optimizations done by the regular expression engine, this will take a painfully long time to run:

    'aaaaaaaaaaaa' =~ /((a{0,5}){0,5}){0,5}[c]/  

And if you used *’s instead of limiting it to 0 through 5 matches, then it would take forever–or until you ran out of stack space. A powerful tool for optimizing such beasts is what is known as an “independent group”, which does not backtrack (see (?maiorquepattern)). Note also that zero-length look-ahead/look-behind assertions will not backtrack to make the tail match, since they are in “logical” context: only whether they match is considered relevant. For an example where side-effects of look-ahead might have influenced the following match, see (?maiorquepattern).

Version 8 Regular Expressions

In case you’re not familiar with the “regular” Version 8 regex routines, here are the pattern-matching rules not described above. Any single character matches itself, unless it is a metacharacter with a special meaning described here or above. You can cause characters that normally function as metacharacters to be interpreted literally by prefixing them with a “\” (e.g., “\.” matches a “.”, not any character; “\\” matches a “\”). A series of characters matches that series of characters in the target string, so the pattern blurfl would match “blurfl” in the target string. You can specify a character class, by enclosing a list of characters in [], which will match any one character from the list. If the first character after the “[" is "^", the class matches any character not in the list. Within a list, the "-" character specifies a range, so that a-z represents all characters between "a" and "z", inclusive. If you want either "-" or "]” itself to be a member of a class, put it at the start of the list (possibly after a “^”), or escape it with a backslash. “-” is also taken literally when it is at the end of the list, just before the closing “]”. (The following all specify the same class of three characters: [-az], [az-], and [a\-z]. All are different from [a-z], which specifies a class containing twenty-six characters.) Also, if you try to use the character classes \w, \W, \s, \S, \d, or \D as endpoints of a range, that’s not a range, the “-” is understood literally. Note also that the whole range idea is rather unportable between character sets–and even within character sets they may cause results you probably didn’t expect. A sound principle is to use only ranges that begin from and end at either alphabets of equal case ([a-e], [A-E]), or digits ([0-9]). Anything else is unsafe. If in doubt, spell out the character sets in full. Characters may be specified using a metacharacter syntax much like that used in C: “\n” matches a newline, “\t” a tab, “\r” a carriage return, “\f” a form feed, etc. More generally, \nnn, where nnn is a string of octal digits, matches the character whose ASCII value is nnn. Similarly, \xnn, where nn are hexadecimal digits, matches the character whose ASCII value is nn. The expression \cx matches the ASCII character control-x. Finally, the “.” metacharacter matches any character except “\n” (unless you use /s). You can specify a series of alternatives for a pattern using “” to separate them, so that feefiefoe will match any of “fee”, “fie”, or “foe” in the target string (as would f(eio)e). The first alternative includes everything from the last pattern delimiter (“(“, “[", or the beginning of the pattern) up to the first "", and the last alternative contains everything from the last "" to the next pattern delimiter. That's why it's common practice to include alternatives in parentheses: to minimize confusion about where they start and end. Alternatives are tried from left to right, so the first alternative found for which the entire expression matches, is the one that is chosen. This means that alternatives are not necessarily greedy. For example: when matching foofoot against "barefoot", only the "foo" part will match, as that is the first alternative tried, and it successfully matches the target string. (This might not seem important, but it is important when you are capturing matched text using parentheses.) Also remember that "" is interpreted as a literal within square brackets, so if you write [feefiefoe] you’re really only matching [feio]. Within a pattern, you may designate subpatterns for later reference by enclosing them in parentheses, and you may refer back to the nth subpattern later in the pattern using the metacharacter \n. Subpatterns are numbered based on the left to right order of their opening parenthesis. A backreference matches whatever actually matched the subpattern in the string being examined, not the rules for that subpattern. Therefore, (00x)\d*\s\1\d* will match “0×1234 0×4321″, but not “0×1234 01234″, because subpattern 1 matched “0x”, even though the rule 00x could potentially match the leading 0 in the second number.

Warning on \1 vs $1

Some people get too used to writing things like:

    $pattern =~ s/(\W)/\\\1/g;  

This is grandfathered for the RHS of a substitute to avoid shocking the sed addicts, but it’s a dirty habit to get into. That’s because in PerlThink, the righthand side of a s/// is a double-quoted string. \1 in the usual double-quoted string means a control-A. The customary Unix meaning of \1 is kludged in for s///. However, if you get into the habit of doing that, you get yourself into trouble if you then add an /e modifier.

    s/(\d+)/ \1 + 1 /eg;     # causes warning under -w  

Or if you try to do

    s/(\d+)/\1000/;  

You can’t disambiguate that by saying \{1}000, whereas you can fix it with ${1}000. The operation of interpolation should not be confused with the operation of matching a backreference. Certainly they mean two different things on the left side of the s///.

Repeated patterns matching zero-length substring

WARNING: Difficult material (and prose) ahead. This section needs a rewrite. Regular expressions provide a terse and powerful programming language. As with most other power tools, power comes together with the ability to wreak havoc. A common abuse of this power stems from the ability to make infinite loops using regular expressions, with something as innocuous as:

    'foo' =~ m{ ( o? )* }x;  

The o? can match at the beginning of ‘foo’, and since the position in the string is not moved by the match, o? would match again and again because of the * modifier. Another common way to create a similar cycle is with the looping modifier //g:

    @matches = ( 'foo' =~ m{ o? }xg ,1,5,UNIX_TIMESTAMP());  

or

    print "match: menorque$&maiorque\n" while 'foo' =~ m{ o? }xg;  

or the loop implied by split(). However, long experience has shown that many programming tasks may be significantly simplified by using repeated subexpressions that may match zero-length substrings. Here’s a simple example being:

    @chars = split //, $string;    # // is not magic in split    ($whitewashed = $string) =~ s/()/ /g; # parens avoid magic s// /  

Thus Perl allows such constructs, by forcefully breaking the infinite loop. The rules for this are different for lower-level loops given by the greedy modifiers *+{}, and for higher-level ones like the /g modifier or split() operator. The lower-level loops are interrupted (that is, the loop is broken) when Perl detects that a repeated expression matched a zero-length substring. Thus

   m{ (?: NON_ZERO_LENGTH  ZERO_LENGTH )* }x;  

is made equivalent to

   m{   (?: NON_ZERO_LENGTH )*

        (?: ZERO_LENGTH )?    }x;  

The higher level-loops preserve an additional state between iterations: whether the last match was zero-length. To break the loop, the following match after a zero-length match is prohibited to have a length of zero. This prohibition interacts with backtracking (see “Backtracking”), and so the second best match is chosen if the best match is of zero length.

For example:

    $_ = 'bar';    s/\w??/menorque$&maiorque/g;  

results in "menorquemenorquebmaiorquemenorquemaiorquemenorqueamaiorquemenorquemaiorquemenorquermaiorquemenorquemaiorque”maiorque. At each position of the string the best match given by non-greedy ?? is the zero-length match, and the second best match is what is matched by \w. Thus zero-length matches alternate with one-character-long matches.

Similarly, for repeated m/()/g the second-best match is the match at the position one notch further in the string.

The additional state of being matched with zero-length is associated with the matched string, and is reset by each assignment to pos(). Zero-length matches at the end of the previous match are ignored during split.

Combining pieces together

Each of the elementary pieces of regular expressions which were described before (such as ab or \Z) could match at most one substring at the given position of the input string. However, in a typical regular expression these elementary pieces are combined into more complicated patterns using combining operators ST, ST, S* etc (in these examples S and T are regular subexpressions).

Such combinations can include alternatives, leading to a problem of choice: if we match a regular expression aab against "abc", will it match substring "a" or "ab"? One way to describe which substring is actually matched is the concept of backtracking (see “Backtracking”). However, this description is too low-level and makes you think in terms of a particular implementation.

Another description starts with notions of “better”/”worse”. All the substrings which may be matched by the given regular expression can be sorted from the “best” match to the “worst” match, and it is the “best” match which is chosen. This substitutes the question of “what is chosen?” by the question of “which matches are better, and which are worse?”.

Again, for elementary pieces there is no such question, since at most one match at a given position is possible. This section describes the notion of better/worse for combining operators. In the description below S and T are regular subexpressions.

ST

Consider two possible matches, AB and A'B', A and A' are substrings which can be matched by S, B and B' are substrings which can be matched by T.

If A is better match for S than A', AB is a better match than A'B'.

If A and A' coincide: AB is a better match than AB' if B is better match for T than B'.

ST

When S can match, it is a better match than when only T can match.

Ordering of two matches for S is the same as for S. Similar for two matches for T.

S{REPEAT_COUNT}
Matches as SSS...S (repeated as many times as necessary).
S{min,max}
Matches as S{max}S{max-1}...S{min+1}S{min}.
S{min,max}?
Matches as S{min}S{min+1}...S{max-1}S{max}.
S?, S*, S+
Same as S{0,1}, S{0,BIG_NUMBER}, S{1,BIG_NUMBER} respectively.
S??, S*?, S+?
Same as S{0,1}?, S{0,BIG_NUMBER}?, S{1,BIG_NUMBER}? respectively.
(?maiorqueS)
Matches the best match for S and only that.
(?=S), (?menorque=S)
Only the best match for S is considered. (This is important only if S has capturing parentheses, and backreferences are used somewhere else in the whole regular expression.)
(?!S), (?menorque!S)
For this grouping operator there is no need to describe the ordering, since only whether or not S can match is important.
(??{ EXPR })
The ordering is the same as for the regular expression which is the result of EXPR.
(?(condition)yes-patternno-pattern)
Recall that which of yes-pattern or no-pattern actually matches is already determined. The ordering of the matches is the same as for the chosen subexpression.

The above recipes describe the ordering of matches at a given position. One more rule is needed to understand how a match is determined for the whole regular expression: a match at an earlier position is always better than a match at a later position.

Creating custom RE engines

Overloaded constants (see overload) provide a simple way to extend the functionality of the RE engine.

Suppose that we want to enable a new RE escape-sequence \Y which matches at boundary between white-space characters and non-whitespace characters. Note that (?=\S)(?menorque!\S)(?!\S)(?menorque=\S) matches exactly at these positions, so we want to have each \Y in the place of the more complicated version. We can create a module customre to do this:

    package customre;    use overload;

    sub import {      shift;      die "No argument to customre::import allowed" if @_;      overload::constant 'qr' =maiorque \&convert;    }

    sub invalid { die "/$_[0]/: invalid escape '\\$_[1]'"}

    my %rules = ( '\\' =maiorque '\\',    'Y' =maiorque qr/(?=\S)(?menorque!\S)(?!\S)(?menorque=\S)/ );    sub convert {      my $re = shift;      $re =~ s{                \\ ( \\  Y . )              }              { $rules{$1} or invalid($re,$1) }sgex;      return $re;    }  

Now use customre enables the new escape in constant regular expressions, i.e., those without any runtime variable interpolations. As documented in overload, this conversion will work only over literal parts of regular expressions. For \Y$re\Y the variable part of this regular expression needs to be converted explicitly (but only if the special meaning of \Y should be enabled inside $re):

    use customre;    $re = menorquemaiorque;    chomp $re;    $re = customre::convert $re;    /\Y$re\Y/;  

BUGS

This document varies from difficult to understand to completely and utterly opaque. The wandering prose riddled with jargon is hard to fathom in several places.

This document needs a rewrite that separates the tutorial content from the reference content.

SEE ALSO

perlop/”Regexp Quote-Like Operators”.

perlop/”Gory details of parsing quoted constructs”.

perlfaq6.

perlfunc/pos.

perllocale.

Mastering Regular Expressions by Jeffrey Friedl, published by O’Reilly and Associates.

Enviado em Referencia | Deixar um comentário »

Creating a Windows Service through Visual Studio.NET

Publicado por agostinhojr em 21 Março, 2007

 

Creating a Windows Service through Visual Studio.NET

Synopsis:

Services run in the Windows operating system as a part of the operating system. These components activate when the operating system boots and keep functioning until the operating system is shut down. This article is a walk through that guides you how to create your own Windows services through Visual Studio.NET.

Note: These concepts do not apply to Windows 9x and Windows Me operating systems.

Defining the Problem:

There are often times when you would have felt the need to create some module or part of your application that would boot up with the operating system and stays functioning until the operating system is not shut down or some type of process that would repeat itself after a specific period of time and etc.

Defining the Solution:

Cases that have been mentioned above require to create serviced components. A serviced component runs as a service in the Windows operating system. If you have worked on Windows NT or Windows 2000 platforms, you would know about many Windows services like Print Spooler Service, Fax Service, Event Log and etc. All these services activate with the operating system and perform different operations related to operating system or the software application along with which they get installed. Although services can automatically start themselves, but you can also change their status by altering their Startup Type property to Manual or Disabled through the Service Control Manager (SCM).

Getting Started

Lets now start with the process of creating a Windows service of our own. In this article I will be creating a Windows service that deletes records from a table after an interval of two minutes. The service will also write entries in a log file of its own.

Open up Visual Studio and select File-New-Project. From the project type window that appears select the Windows Service template. Name the project and select the location where you want this project to be created. In the case of this example, I have named my project as AspaService.

(Figure shows Window Service template selected for creating the new project)

Click the OK button. Visual Studio.NET creates a default template and displays the design view of a page named as Service1.vb, as also shown in the figure below.

(Figure shows default template for the Window Service project created by VS.NET)

In the Properties pane, change the File Name property of the file to DeleteRecords.vb. Changing the file name also changes the name of the file on the designer tab.

Now place a Timer control and an EventLog control from the Toolbox-Components menu on the designer. See the following figure.

(Figure shows the Timer and EventLog components placed on the designer)

After placing the components, double click on the designer window to open up its source file. In the source file expand the Component Designer Generated Code section. Under the Sub New sub procedure write down the following lines of code after the InitializeComponent() method.

If Not EventLog.SourceExists(“MySource”) Then
EventLog.CreateEventSource(“MySource”, “MyNewLog”)
End If

EventLog1.Source = “MySource”
EventLog1.Log = “MyNewLog”

See the following figure for a more clear view.

(Figure shows the code written for creating an event log source)

The code here checks to see if an eventlog source file by name of MySource exists. If it does that file would be assigned to our EventLog object as the source file, otherwise the file would first be created and then be used.

Close the Component Designer Generated Code region by clicking on the (-) sign next to it. This would close the node and the code in it. Notice that there are two sub procedures that are also existing in the source file. These have been shown below in the figure.

(Figure shows the events of the Windows service generated in the default template by VS.NET)

The OnStart() and OnStop() are among two of the events of a Windows service. There are others also like OnContinue and OnPause() etc, but these are the two that are created for us in the default template. The OnStart() event occurs when the service starts and the OnStop() event occurs when the serviced component is stopped. Before writing code into these events first of all include the following namespace at the top of your source file.

                     

Imports System.Data.SqlClient

 
       

Since the service would be used to delete records from a table after a specific period of time therefore this namespace is required to declare the objects that would be used for connecting and executing the SQL statements on the database server.

After this declare a variable of date data type in the class and initialize it with the current date and time. See the following figure.

(Figure shows the declaring and the initializing of a Date data type variable)

As shown in the figure a variable named _PreviousTime of data type Date is declared and is initialized with the current date and time of the system, which is assigned to it through the Now() function.

Now from the designer view, double click on the timer control and write the code within its Elapsed event as shown in the figure below.

(Figure shows the code for the Elapsed event of the Timer Control)

This event is fired by the timer after every millisecond (the default behavior which can be changed). On being fired, it compares the current minute of the system time by subtracting two from it with the minute of the time stored in the _PreviousTime variable. On having a match it would call the custom defined procedure DeleteRecords(), that would actually delete the records from the table in the database server. The code for DeleteRecords() is as shown below in the figure.

(Figure shows code for the custom sub procedure DeleteRecords( ))

The code in the procedure is simple. It creates a connection object that is being used to connect to the Pubs database on the local system server. A command object is also created that is provided the connection object and the query parameters in the constructor. The temp is a table that you will have to create yourself as it is not provided in the Pubs database by default.

Within the Try block the command object is executed and incase of a successful execution the entry is listed into the log file that was created earlier in this project. The Try and Catch section is to handle any types of errors that may arise and incase if an error is encountered it would be written into the same eventlog file that was created earlier.

Having done this, add some lines of code to the OnStart() and OnStop() events of the service also. See the following figure.

(Figure Shows the code to be written in the OnStart and OnStop events)

When the service starts it will make an entry into the log file stating “In OnStart” and after that it would start the timer. Similarly, when the service is stopped, an entry is made in the log file and the timer is stopped.

This completes the coding required to create the service. But the service cannot be just tested by clicking F5. For testing a service it is required to be installed first.

Creating an Installer for the service

Return to the designer view and click on the background of the designer to select it.

Once selected change the Name and ServiceName properties to AspaService.

Right click on the designer and select the Add Installer option. Visual Studio will create a new component class named as ProjectInstaller. The design view of the class will show two installers on the designer. The ServiceInstaller1 is to install your service and the other ServiceProcessInstaller1 is to install the process associated with the service. See the following figure.

(Figure shows the design view for the Project Installer having two installer placed by default)

Click on ServiceInstaller1, set the Name property to AspaService and StartType property to Automatic.

Now click on ServiceProcessInstaller1 to select it. Set the Account property to LocalSystem. Incase if you leave it as User, you would be required to provide a username and a password during installation. The other two options for the property i.e. LocalService and NetworkService are only applicable on WindowsXP.

Creating a Setup Project

For creating a setup project, select File-New-Project.

From the New Project window, select Setup and Deployment Projects from Project Types and select Setup Project from the Templates pane.

Name the project as Aspa Service Setup and select the Add to Solution radio button option. See the figure below for a demonstration.

(Figure shows settings for the new Setup Project)

Click OK. Visual studio will create a default template for you.

In the solution explorer right click on the Aspa Service Setup, point to Add, then choose Project Output. The Add Project Output Group dialog appears.

Make sure that AspaService is selected in the Project box. From the list box below the Project box, select Primary Output. This has been displayed in the figure below.

(Figure shows settings for Add Project Output Group)

Click OK. A project item for the primary output of AspaService is added to the setup project. Now add a custom action to install the AspaService.exe file.

Adding a Custom Action to the Setup Project

In Solution Explorer, right-click the setup project, point to View, then choose Custom Actions. The Custom Actions editor appears.

In the Custom Actions editor, right-click the Custom Actions node and choose Add Custom Action. The Select Item in Project dialog box appears.

Double-click the Application Folder in the list box to open it, select Primary Output from AspaService(Active), and click OK. The primary output is added to all four nodes of the custom actions — Install, Commit, Rollback, and Uninstall.

Now Build the Setup Project.

Installing the Service

Browse to where the setup project has been saved and double click the .msi file. Install the service and then view it through the SCM. The SCM can be opened from Start-Programs-Administrative Tools-Services menu. In the SCM the service will appear by the name of AspaService or any other name that you have given to the service.

The Service in action

Click on the service to select it. Then right click and select the Start option. This would start your service and it would also write down an entry into the log file. To view the log file open the Event Viewer from the Administrative Tools menu. Within the Event Viewer click on MyNewLog in the left pane and then from the right pane double click on the first event entry. See the description section and it will show In OnStart, which is what you specified in the OnStart event of your service.

Create a table in the pubs database by name of temp and fill it with some records. After an interval of two minutes review the table and you would see that all of the records from the table have been deleted. Another entry for the successful deletion of the records will also be listed in the log and you can view that from the Event Viewer as well.

Uninstalling the Service

To uninstall the service simply rerun the .msi file. Select the Remove option from the wizard window and the service will be uninstalled automatically.

Categories:

Enviado em .NET, windows | Deixar um comentário »