Wednesday, December 15, 2010
Monday, August 30, 2010
Queue Programe which stores functions with different argument
#include windows.h
#include stdio.h
#include malloc.h
#include stdlib.h //put include file in < > during execution.
#using system.dll
using namespace System;
using namespace System::Timers;
#define TRUE 1
#define FALSE 0
typedef int BOOL;
HANDLE g_hISemhandler = NULL;
HANDLE g_hRSemhandler = NULL;
typedef DWORD RADRES;
typedef unsigned char BYTE;
int RemoveFromQueue (void);
int ReadQueue(void);
RADRES RdsStartCapture(BOOL, BOOL);
RADRES RdsStopCapture(BOOL, BOOL);
RADRES FMRadio_SetVolume(BYTE);
DWORD InsertThread (LPVOID lpdwThreadParam );
DWORD ReadThread (LPVOID lpdwThreadParam );
/*************Timer for inserting functions in to Queue****************/
public ref class Timer1
{
private:
static System::Timers::Timer^ aTimer;
public:
static void Demo()
{
aTimer = gcnew System::Timers::Timer(5000);
aTimer->Elapsed += gcnew ElapsedEventHandler( Timer1::OnTimedEvent );
aTimer->Interval = 5000;
aTimer->Enabled = true;
GC::KeepAlive(aTimer);
}
private:
static void OnTimedEvent( Object^ source, ElapsedEventArgs^ e )
{
ReleaseSemaphore(g_hISemhandler,1,NULL);
Console::WriteLine("insert timer event {0}", e->SignalTime);
}
};
/***********Timer for reading and removing functions from Queue**********/
public ref class Timer2
{
private:
static System::Timers::Timer^ aTimer;
public:
static void Demo()
{
aTimer = gcnew System::Timers::Timer(5000);
aTimer->Elapsed += gcnew ElapsedEventHandler( Timer2::OnTimedEvent );
aTimer->Interval = 3000;
aTimer->Enabled = true;
GC::KeepAlive(aTimer);
}
private:
static void OnTimedEvent( Object^ source, ElapsedEventArgs^ e )
{
ReleaseSemaphore(g_hRSemhandler,1,NULL);
Console::WriteLine("read timer event {0}", e->SignalTime);
}
};
/************Queue structure**************/
struct Queue
{
RADRES(*function_1arg)(BOOL, BOOL);
RADRES(*function_2arg)(BYTE);
BOOL arg1;
BOOL arg2;
BYTE arg3;
struct Queue *node;
} *front = NULL;
/************Insert Class for different InsertIntoQueue method overloading **************/
class Insert{
public:
void InsertIntoQueue (RADRES (*function)(BOOL, BOOL),BOOL a, BOOL b)
{
struct Queue *temp, *q;
temp = (struct Queue *)malloc(sizeof(struct Queue));
temp->function_1arg = *function;
temp->function_2arg = NULL;
temp->arg1 = a;
temp->arg2 = b;
temp->node=NULL;
if(front == NULL)
front = temp;
else
{
q = front;
while(q->node != NULL)
q = q->node;
q->node = temp;
}
printf("inserted into buffer\n");
}
void InsertIntoQueue (RADRES (*function)(BYTE),BYTE a)
{
struct Queue *temp, *q;
temp = (struct Queue *)malloc(sizeof(struct Queue));
temp->function_2arg = *function;
temp->function_1arg = NULL;
temp->arg3 = a;
temp->node=NULL;
if(front == NULL)
front = temp;
else
{
q = front;
while(q->node != NULL)
q = q->node;
q->node = temp;
}
printf("inserted into buffer\n");
}
};
/************main function **************/
int main()
{
g_hISemhandler = CreateSemaphore(NULL,0,1, _T("insertSem"));
g_hRSemhandler = CreateSemaphore(NULL,0,1, _T("readSem"));
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&InsertThread, (LPVOID)NULL,0,NULL);
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&ReadThread, (LPVOID)NULL,0,NULL);
getchar();
}
///////////////////////////////////////////////////////////////////////////////
/******************************************************************************
* FUNCTION: RemoveFromQueue
* DESCRIPTION: removes the functions from Queue
* ARGS:
*
* RETURNS: TRUE for SUCESS and FALSE for FAILURE
******************************************************************************/
int RemoveFromQueue(void)
{
struct Queue *temp;
if(front == NULL)
return FALSE;
else
{
temp = front;
front = front->node;
free(temp);
printf("Function removed from buffer\n");
return TRUE;
}
}
RADRES RdsStartCapture(BOOL a, BOOL b)
{
printf("RdsStartCapture \n a =%d \t b=%d \n", a, b);
return TRUE;
}
RADRES RdsStopCapture(BOOL a, BOOL b)
{
printf("RdsStopCapture \n a =%d \t b=%d \n", a, b);
return TRUE;
}
RADRES FMRadio_SetVolume(BYTE a)
{
printf("RdsStopCapture \n a =%d \n", a);
return TRUE;
}
/******************************************************************************
* FUNCTION: ReadQueue
* DESCRIPTION: calles the function in Queue(FIFO) and removes from the queue
* ARGS:
*
* RETURNS: TRUE for SUCESS and FALSE for FAILURE
******************************************************************************/
int ReadQueue(void)
{
if(front != NULL && front->function_1arg!= NULL)
{
front->function_1arg(front->arg1,front->arg2);
//RETAILMSG(1, (TEXT("Calling Buffered function\n")));
RemoveFromQueue(); //removing function from the Queue.
return TRUE;
}
else if(front != NULL && front->function_2arg!= NULL)
{
front->function_2arg(front->arg3);
//RETAILMSG(1, (TEXT("Calling Buffered function\n")));
RemoveFromQueue(); //removing function from the Queue.
}
else
{
printf("Buffer Is Empty\n");
//RETAILMSG(1, (TEXT("Buffer Is Empty\n")));
}
return FALSE;
}
DWORD InsertThread (LPVOID lpdwThreadParam )
{
int i=4,j=0,k=2;
Insert ins;
printf("Insert thread begins.... \n");
Timer1::Demo();
while(1)
{
WaitForSingleObject(g_hISemhandler, 10000);
ins.InsertIntoQueue(RdsStartCapture,5,9);
ins.InsertIntoQueue(FMRadio_SetVolume,2);
printf("\n\n");
}
return TRUE;
}
DWORD ReadThread (LPVOID lpdwThreadParam )
{
printf("Read thread begins.... \n");
Timer2::Demo();
while(1)
{
WaitForSingleObject(g_hRSemhandler, 10000);
ReadQueue();
printf("\n\n");
}
return TRUE;
}
//End of PROG
Wednesday, July 21, 2010
VLSI and hardware engineering interview questions
2. Draw Vds-Ids curve for a MOSFET. Now, show how this curve changes (a) with increasing Vgs (b) with increasing transistor width (c) considering Channel Length Modulation
3. Explain the various MOSFET Capacitances & their significance
4. Draw a CMOS Inverter. Explain its transfer characteristics
5. Explain sizing of the inverter
6. How do you size NMOS and PMOS transistors to increase the threshold voltage?
7. What is Noise Margin? Explain the procedure to determine Noise Margin
8. Give the expression for CMOS switching power dissipation
9. What is Body Effect?
10. Describe the various effects of scaling
11. Give the expression for calculating Delay in CMOS circuit
12. What happens to delay if you increase load capacitance?
13. What happens to delay if we include a resistance at the output of a CMOS circuit?
14. What are the limitations in increasing the power supply to reduce delay?
15. How does Resistance of the metal lines vary with increasing thickness and increasing length?
16. You have three adjacent parallel metal lines. Two out of phase signals pass through the outer two metal lines. Draw the waveforms in the center metal line due to interference. Now, draw the signals if the signals in outer metal lines are in phase with each other
17. What happens if we increase the number of contacts or via from one metal layer to the next?
18. Draw a transistor level two input NAND gate. Explain its sizing (a) considering Vth (b) for equal rise and fall times
19. Let A & B be two inputs of the NAND gate. Say signal A arrives at the NAND gate later than signal B. To optimize delay, of the two series NMOS inputs A & B, which one would you place near the output?
20. Draw the stick diagram of a NOR gate. Optimize it
21. For CMOS logic, give the various techniques you know to minimize power consumption
22. What is Charge Sharing? Explain the Charge Sharing problem while sampling data from a Bus
23. Why do we gradually increase the size of inverters in buffer design? Why not give the output of a circuit to one large inverter?
24. In the design of a large inverter, why do we prefer to connect small transistors in parallel (thus increasing effective width) rather than lay out one transistor with large width?
25. Given a layout, draw its transistor level circuit. (I was given a 3 input AND gate and a 2 input Multiplexer. You can expect any simple 2 or 3 input gates)
26. Give the logic expression for an AOI gate. Draw its transistor level equivalent. Draw its stick diagram
27. Why don’t we use just one NMOS or PMOS transistor as a transmission gate?
28. For a NMOS transistor acting as a pass transistor, say the gate is connected to VDD, give the output for a square pulse input going from 0 to VDD
29. Draw a 6-T SRAM Cell and explain the Read and Write operations
30. Draw the Differential Sense Amplifier and explain its working. Any idea how to size this circuit? (Consider Channel Length Modulation)
31. What happens if we use an Inverter instead of the Differential Sense Amplifier?
32. Draw the SRAM Write Circuitry
33. Approximately, what were the sizes of your transistors in the SRAM cell? How did you arrive at those sizes?
34. How does the size of PMOS Pull Up transistors (for bit & bit- lines) affect SRAM’s performance?
35. What’s the critical path in a SRAM?
36. Draw the timing diagram for a SRAM Read. What happens if we delay the enabling of Clock signal?
37. Give a big picture of the entire SRAM Layout showing your placements of SRAM Cells, Row Decoders, Column Decoders, Read Circuit, Write Circuit and Buffers
38. In a SRAM layout, which metal layers would you prefer for Word Lines and Bit Lines? Why?
39. How can you model a SRAM at RTL Level?
40. What’s the difference between Testing & Verification?
41. For an AND-OR implementation of a two input Mux, how do you test for Stuck-At-0 and Stuck-At-1 faults at the internal nodes? (You can expect a circuit with some redundant logic)
42. What is Latch Up? Explain Latch Up with cross section of a CMOS Inverter. How do you avoid Latch Up?
Wednesday, July 14, 2010
Microsoft Win32 interview questions
- Tell the differences between Windows 95 and Windows NT? Lack of Unicode implementation for most of the functions of Win95. Different extended error codes. Different number window and menu handles. Windows 95 implements some window management features in 16 bits. Windows 95 uses 16-bit world coordinate system and the coordinates restricted to 32K. Deletion of drawing objects is different. Windows 95 does not implement print monitor DLLs of Windows NT. Differences in registry. Windows 95 does not support multiprocessor computers. NT implementation of scheduler is quite different. Different driver models. Win95 was built with back-compatibility in mind and ill-behaving 16-bit process may easily corrupt the system. Win95 starts from real DOS, while WinNT uses DOS emulation when one needs a DOS. Win95’s FAT is built over 16-bit win3.1 FAT (not FAT32!, actually, Win95’s FAT contains two FATs).
- What is the effective way of DIB files management? A: Memory-mapped file is the best choice for device-independent bitmaps. MMF allows to map the file to RAM/SWAP addresses and to let Windows handle all load/unload operations for the file.
- What should you be aware of if you design a program that runs days/weeks/months/years? A: When your program should run for a long time, you should be careful about heap allocations, because if you use new/delete intensively in your application, the memory becomes highly fragmented with a time. It is better to allocate all necessary memory in this case that many times small blocks. You should be especially careful about CString class which allocates permanent DLL
- What are the advantages of using DLL’s? DLLs are run-time modular. DLL is loaded when the program needs it. Used as a code sharing between executables.
- What are the different types of DLL’s? A: Extension, Regular and pure Win32 DLL (without MFC)
- What are the differences between a User DLL and an MFC Extension DLL? A: Extension DLL supports a C++ interface, i.e. can export whole C++ classes and the client may construct objects from them. Extension DLL dynamically links to MFC DLLs (those which name starts with MFC??.DLL) and to be synchronous with the version it was developed for. Extension DLL is usually small (simple extension DLL might be around 10K) Regular DLL can be loaded by any Win32 environment (e.g. VB 5) Big restriction is that regular DLL may export only C-style functions. Regular DLLs are generally larger. When you build a regular DLL, you may choose a static link (in this case MFC library code is copied to your DLL) and dynamic (in this case you would need MFC DLLs to be presented on the target machine)
- What do you have to do when you inherit from two CObject-based classes? A: First of all, this is a bad idea does not matter what tells you interviewer. Secondly, if you forced to use condemned rhombus structure, read Technical Note 16 in MSDN, which discusses why MFC does not support multiple inheritance and what to do in case you still need it (there are a few problems with CObject class, such as incorrect information, returned by IsKindOf() of CObject for MI, etc.)
- What are the additional requirements for inheritance from CWnd-based classes? A: Again, this is the bad idea. Try to find alternative solution. Anyway, if you have to multiply inherit from CWnd-based class, the following are additional requirements to the above conditions (again, this is extremely bad question for interview!!!): There must be only one CWnd-derived base class. The CWnd-derived base class must be the first (or left-most) base class.
- What is a "mutex"? A: Mutexes are the mechanism of process synchronization that might be used to synchronize data across multiple processes. Mutex is a waitable object while a critical section is not. Mutexes are significantly slower than critical sections.
- What’s the difference between a "mutex" and a "critical section"? Critical section provides synchronization means for one process only, while mutexes allow data synchronization across processes.
- What might be wrong with the following pseudo-code:
FUNCTION F
BEGIN
INT I=2
DO
I = I + 1
IF I = 4 THEN BREAK
END DO
END
A:This code is not thread safe. Suppose one thread increments I to 3 and then returns to the beginning of DO statement. Then it increments I to 4 and now context switch happens. Second thread increments I to 5. From this moment the code shown will execute forever until some external force intervention. Solution is obviously using some synchronization object to protect I from being changed by more than one thread. - What is a deadlock ? A: A deadlock, very simply, is a condition in which two or more threads wait for each other to release a shared resource before resuming their execution. Because all threads participating in a deadlock are suspended and cannot, therefore, release the resources they own, no thread can continue, and the entire application (or, worse, more than one application if the resources are shared between threads in multiple applications) appears to hang.
- How can we create thread in MFC framework? A: Using AfxBeginThread.
- What types of threads are supported by MFC framework? A: Working thread and windows thread. Working thread usually does not have a user interface and easier to use. Windows thread has an user interface and usually used to improve responsiveness of the user input. Message Map
- When ON_UPDATE_COMMAND_UI is called? (message may vary) A: When a user of your application pulls down a menu, each menu item needs to know whether it should be displayed as enabled or disabled. The target of a menu command provides this information by implementing an ON_UPDATE_COMMAND_UI handler.
- What is a "hook"? A: A point in the Windows message-handling mechanism where an application can install a subroutine to monitor messages. You need hooks to implement your own Windows message filter.
- What are the difference between MFC Exception macros and C++ exception keywords? A:Actually, MFC macros may accept exception of only CException class or class, derived from CException, where as C++ exception mechanism accepts exception of ANY type Reusable Control Class
- How would you set the background of an edit control to a customized color? A: You have several choices, but the simplest one is subclassing. Kruglinski in his "Inside Visual C++" describes pretty well this process. Generally, you derive the class from none control class, override the messages you want (like WM_CTLCOLOR) and then in init function like OnInitialUpdate of CDialog, subclass the control with SubclassDlgItem().
- What is Message Reflection? How could you accomplish the above task using message reflection? A: See Technical Note 62 of MSDN. Usually, message is handled in the parent class that means you have to override message handler for each parent. Sometimes it is nice to handle a message in the control itself, without parent invocation. Such handling mechanism is called message reflection. Control "reflects" message to itself and then processes it. Use ON_
_REFLECT macro to create a reflected message. - What is the command routing in MFC framework? A: CView => CDocument => CFrameWnd => CWinApp
- What’s the purpose of CView class? CDocument class? What are relationships between them? A: The CView class provides the basic functionality for user-defined view classes. A view is attached to a document and acts as an intermediary between the document and the user: the view renders an image of the document on the screen or printer and interprets user input as operations upon the document. The CDocument class provides the basic functionality for user-defined document classes. A document represents the unit of data that the user typically opens with the File Open command and saves with the File Save command. Users interact with a document through the CView object(s) associated with it. A view is a child of a frame window. The relationship between a view class, a frame window class, and a document class is established by a CDocTemplate object. A view can be attached to only one document, but a document can have multiple views attached to it at once.
- What class is responsible for document template in MDI application? A: CMultiDocTemplate.
- What function must be used to add document template? A: AddDocTemplate.
- What the main objects are created for SDI and MDI applications? A: CWinApp - application object. For MDI application with New document implementation CDocTemplate, CDocument, CView, CMainFrame. If your application is SDI, your CMainFrame class is derived from class CFrameWnd. If your application is MDI, CMainFrame is derived from class CMDIFrameWnd. For MDI application CMDIChildWindow is also created.
- We have a loop for 800,000. It fails on 756,322. How can we get the information before it fails? A: You could think of several way to debug this: Set the condition in debugger to stop when loop is passed around 756321 times. Throw an exception within a loop (may be not the best idea since exception does not show you the exact location of the fail. Create a log file and to put detailed information within a loop.
- Our Debug version works fine, but Release fails. What should be done? A: There are four differences between debug and release builds:
- heap layout (you may have heap overwrite in release mode - this will cause 90% of all problems),
- compilation (check conditional compilation statements, assertion functions etc.),
- pointer support (no padding in release mode which may increase chances of a pointer to point into sky)
- optimization.
MFC interview questions
1. What is the base class for MFC Framework ?
2. If i derive a new class from CObject what are the basic features my derived wil get ?
3. What is the use of CCmdTarget ?
4. What is document-view architecture ? Give me one real time example for SDI ?
5. Can you explaing the relashionship between document,frame and view ?
6. How to access document object from view ?
5. What is the entry point for window based applications ?
6. Explain the flow for a simple win32 based application ?
7. How to handle command line arguements from simple MFC application ?
8. What is model and modeless dialog box ? Give some examples?
9. How to create open & save dialogs ?
10.What is CSingleDocTemplate?
11.What is the difference between hinsrtance and hprevinstance in WinMain function?
12.Explaing about MDI and CMultiDocTemplate ?
13.Tell me the different controls in MFC ?
14. What is the use of OninitDialog ?
15. What is the use of UpdateData funciton ?
16.What is the difference between GetMessage and PeekMessage ?
17.How to update all the views whenver document got updated ?
18.How to handle RTTI in MFC ?
19.What is serialization ?which function is responsible for serializing data ?
20.What is CArchive class dowes?
21.What is thread & process?
22.Explain about different kinds of threads in MFC?
23.Tell me about different kinds of synchranization objects ?
24.what is the use of Mutex and critical section ?
25.What is socket?
26.What is the difference between Synchronous sockets and asynchronous sockets?
27.Have you ever used win32 APIs ?
28.What is the difference between ANSI Code and UNICODE ?
29.What is the difference between regular dlls and extended dlls?
30.what is the use of AFX_MANAGE_STATE ?
31. What’s the difference between PostMessage and SendMessage?
32. Describe the Document/View architecture.
33. What’s the difference between Modal and Modeless Dialog?
34. How to create a Modeless Dialog?
35. How to setup a timer?
36. Name the Synchronization objects.
37. What is a critical section and how is it implemented?
38. What is CMutex?
39. Given two processes, how can they share memory?
38. What is a message map, and what is the advantage of a message map over virtual functions?
40. What is the difference between ASSERT and VERIFY?
41. Why wizards generate enum IDD for dialogs?
Monday, July 12, 2010
Driver Programming in Windows (Hello World Programing )
Pre-requisites (all free downloads)
The latest Windows Driver Kit installed. I pulled a copy from one of our internal shares but I just found out that it is now a free download as well (you could only get it shipped to you in the past).
Microsoft Virtual PC. This is to let me test my driver without having to get another machine and finding the right cable to go between them (I'm just lazy). Modifying this tutorial to work with a real machine is pretty trivial.
Debugging Tools for Windows. Visual Studio cannot do kernel-mode debugging and hence you need to use the WinDBG/NTSD/CDB family of debuggers.
Windows XP/2003/Vista installed on VPC. In my case, I have a Win2k3 VPC but depending on which operating system you have, pick the right build environment in the 'Build your driver' section below.
Code for your driver
1. Create a directory where your driver sources will lie. For the following example, all my source files will lie in C:\testdrv
2. Create a file called test.c with the following contents. This is as simple a driver as you can get (in fact, it doesn't even know how to unload itself). When started, it prints a 'Hello World' message which any attached kernel debugger or DbgView will see.#include
3. Create a file called makefile.def with the following line it it. This pulls in the appropriate makefile for your build environment (more on that later). !INCLUDE $(NTMAKEENV)\makefile.def
4. Create a file called sources (note that it doesn't have any extension) with the following contents. This specifies which source files you are compiling, that it will build a driver and the headers and lib files to use.
TARGETNAME = testTARGETPATH = objTARGETTYPE = DRIVER
INCLUDES = %BUILD%\incLIBS = %BUILD%\lib
SOURCES = test.c
Building your driver
1. Click on Start->All Programs->Windows Driver Kits->WDK 6000->Build Environments->Windows Server 2003->Windows Server 2003 x86 Checked Build. I'm picking this since I have a 32-bit Win2k3 VPC - pick the one which matches the closest with your target machine. For example, if you have a physical Windows Vista x64 machine you want to try out your driver on, you would pick 'Windows Vista and Windows Server Longhorn x64 Checked Build Environment'.
This drops you into a command prompt with some nice environment variables (your build environment) already set for you.
2. Change to the directory which has your driver source and run 'build'. This invokes build.exe , the de-facto Microsoft build tool for almost two decades until MSBuild came on the scene (and even now, a lot of product groups still use build.exe). Written by Steve Wood over 15 years ago, this is one tool that has withstood the test of time :-) 1 If you've followed along well, you should see a test.sys and a test.pdb (along with other files) in your object build directory.
Setting up your target machine for kernel debugging
1. To attach a kernel debugger to a running instance of Windows, you need to do some minor configuration. In the target VPC Win2k3 instance, go to My Computer->Properties->Advance->Settings under Startup and Recovery->Edit. You should see a line like multi(0)disk(0)rdisk(0)partition(1)\WINDOWS="Windows Server 2003, Enterprise" /fastdetect /NoExecute=OptOutAdd "/debug /debugport=com1" to the line above (without the quotes).If you're using Windows Vista as your target operating system, you can't use this technique - you'll have to use the inbuilt bcdedit.exe utility.
2. In the virtual machine's settings, redirect the COM port to a pipe called http:////pipe/vpc . What we're doing here is telling Windows to redirect all debug spew to the COM1 port and then telling VPC to redirect COM1 to a named pipe.
3. Restart the virtual machine (the boot settings need a restart to kick in).
4. One final step - running the kernel debugger! Run windbg with the following command-line (if you already have symbols setup correctly, ignore the -y parameter).
windbg-y SRV*c:\symbols*http://msdl.microsoft.com/download/symbols -k com:pipe,port=\\.\pipe\vpc,resets=0,reconnect
This should open up windbg and connect it to your running instance of Win2k3 on VPC.
Registering and running your driver
Whew. Just a couple of steps more and we'll be home. The last 2 things for us to do are to register the driver and then to run it. Our driver currently cannot be unloaded (the ability to do so would just require 4 more lines of code though) so you'll have to restart the machine manually to see new changes reflected.
1. First, let's register the driver. James Brown's tutorial covers some of the ways you can register the driver but (like him), I'll recommend downloading the 'Driver Loader' utility from http://www.osronline.com/ which unfortunately requires a free registration. Run it on your target Win2k3 VPC
2. Copy your drivers' binaries over to the VPC (I typically do this using the shared folder feature). Point Driver Loader to your binary and register your driver. This needs to be done only once irrespective of how many times you rebuild your binaries.
If you've followed along so far, congratulations for you're finally home. Hit 'Start Service' in 'Driver Loader'. This should result in a call to your DriverEntry method and in your WinDBG running on the host computer, you should see this To quote John McClane, Yippie-Ki-ay
Happy hacking!
Notes
1. If you're interested in the internals of build.exe, you should check out the code that ships with Rotor (online cached copy here). However, I haven't checked to see whether it is from the same code base as the real build.exe.
Saturday, July 10, 2010
Basic Linux Commands
mkdir - make directories
Usage
mkdir [OPTION] DIRECTORY
Options
Create the DIRECTORY(ies), if they do not already exist.
Mandatory arguments to long options are mandatory for short options too.
-m, mode=MODE set permission mode (as in chmod), not rwxrwxrwx - umask
-p, parents no error if existing, make parent directories as needed
-v, verbose print a message for each created directory
-help display this help and exit
-version output version information and exit
cd - change directories
Use cd to change directories. Type cd followed by the name of a directory to access that directory.Keep in mind that you are always in a directory and can navigate to directories hierarchically above or below.
mv- change the name of a directory
Type mv followed by the current name of a directory and the new name of the directory.
Ex: mv testdir newnamedir
pwd - print working directory
will show you the full path to the directory you are currently in. This is very handy to use, especially when performing some of the other commands on this page
rmdir - Remove an existing directory
rm -r
Removes directories and files within the directories recursively.
chown - change file owner and group
Usage
chown [OPTION] OWNER[:[GROUP]] FILE
chown [OPTION] :GROUP FILE
chown [OPTION] --reference=RFILE FILE
Options
Change the owner and/or group of each FILE to OWNER and/or GROUP. With --reference, change the owner and group of each FILE to those of RFILE.
-c, changes like verbose but report only when a change is made
-dereference affect the referent of each symbolic link, rather than the symbolic link itself
-h, no-dereference affect each symbolic link instead of any referenced file (useful only on systems that can change the ownership of a symlink)
-from=CURRENT_OWNER:CURRENT_GROUP
change the owner and/or group of each file only if its current owner and/or group match those specified here. Either may be omitted, in which case a match is not required for the omitted attribute.
-no-preserve-root do not treat `/' specially (the default)
-preserve-root fail to operate recursively on `/'
-f, -silent, -quiet suppress most error messages
-reference=RFILE use RFILE's owner and group rather than the specifying OWNER:GROUP values
-R, -recursive operate on files and directories recursively
-v, -verbose output a diagnostic for every file processed
The following options modify how a hierarchy is traversed when the -R option is also specified. If more than one is specified, only the final one takes effect.
-H if a command line argument is a symbolic link to a directory, traverse it
-L traverse every symbolic link to a directory encountered
-P do not traverse any symbolic links (default)
chmod - change file access permissions
Usage
chmod [-r] permissions filenames
r Change the permission on files that are in the subdirectories of the directory that you are currently in. permission Specifies the rights that are being granted. Below is the different rights that you can grant in an alpha numeric format.filenames File or directory that you are associating the rights with Permissions
u - User who owns the file.
g - Group that owns the file.
o - Other.
a - All.
r - Read the file.
w - Write or edit the file.
x - Execute or run the file as a program.
Numeric Permissions:
CHMOD can also to attributed by using Numeric Permissions:
400 read by owner
040 read by group
004 read by anybody (other)
200 write by owner
020 write by group
002 write by anybody
100 execute by owner
010 execute by group
001 execute by anybody
ls - Short listing of directory contents
-a list hidden files
-d list the name of the current directory
-F show directories with a trailing '/'
executable files with a trailing '*'
-g show group ownership of file in long listing
-i print the inode number of each file
-l long listing giving details about files and directories
-R list all subdirectories encountered
-t sort by time modified instead of name
cp - Copy files
cp myfile yourfile
Copy the files "myfile" to the file "yourfile" in the current working directory. This command will create the file "yourfile" if it doesn't exist. It will normally overwrite it without warning if it exists.
cp -i myfile yourfile
With the "-i" option, if the file "yourfile" exists, you will be prompted before it is overwritten.
cp -i /data/myfile
Copy the file "/data/myfile" to the current working directory and name it "myfile". Prompt before overwriting the file.
cp -dpr srcdir destdir
Copy all files from the directory "srcdir" to the directory "destdir" preserving links (-poption), file attributes (-p option), and copy recursively (-r option). With these options, a directory and all it contents can be copied to another dir
ln - Creates a symbolic link to a file.
ln -s test symlink
Creates a symbolic link named symlink that points to the file test Typing "ls -i test symlink" will show the two files are different with different inodes. Typing "ls -l test symlink" will show that symlink points to the file test.
locate - A fast database driven file locator.
slocate -u
This command builds the slocate database. It will take several minutes to complete this command.This command must be used before searching for files, however cron runs this command periodically on most systems.locate whereis Lists all files whose names contain the string "whereis". directory.
more - Allows file contents or piped output to be sent to the screen one page at a time
less - Opposite of the more command
cat - Sends file contents to standard output. This is a way to list the contents of short files to the screen. It works well with piping.
whereis - Report all known instances of a command
wc - Print byte, word, and line countsbg
bg jobs Places the current job (or, by using the alternative form, the specified jobs) in the background, suspending its execution so that a new user prompt appears immediately. Use the jobs command to discover the identities of background jobs.
cal month year - Prints a calendar for the specified month of the specified year.
cat files - Prints the contents of the specified files.
clear - Clears the terminal screen.
cmp file1 file2 - Compares two files, reporting all discrepancies. Similar to the diff command, though the output format differs.
diff file1 file2 - Compares two files, reporting all discrepancies. Similar to the cmp command, though the output format differs.
dmesg - Prints the messages resulting from the most recent system boot.
fg
fg jobs - Brings the current job (or the specified jobs) to the foreground.
file files - Determines and prints a description of the type of each specified file.
find path -name pattern -print
Searches the specified path for files with names matching the specified pattern (usually enclosed in single quotes) and prints their names. The find command has many other arguments and functions; see the online documentation.
finger users - Prints descriptions of the specified users.
free - Displays the amount of used and free system memory.
ftp hostname
Opens an FTP connection to the specified host, allowing files to be transferred. The FTP program provides subcommands for accomplishing file transfers; see the online documentation.
head files - Prints the first several lines of each specified file.
ispell files - Checks the spelling of the contents of the specified files.
kill process_ids
kill - signal process_ids
kill -l
Kills the specified processes, sends the specified processes the specified signal (given as a number or name), or prints a list of available signals.
killall program
killall - signal program
Kills all processes that are instances of the specified program or sends the specified signal to all processes that are instances of the specified program.
mail - Launches a simple mail client that permits sending and receiving email messages.
man title
man section title - Prints the specified man page.
ping host - Sends an echo request via TCP/IP to the specified host. A response confirms that the host is operational.
reboot - Reboots the system (requires root privileges).
shutdown minutes
shutdown -r minutes
Shuts down the system after the specified number of minutes elapses (requires root privileges). The -r option causes the system to be rebooted once it has shut down.
sleep time - Causes the command interpreter to pause for the specified number of seconds.
sort files - Sorts the specified files. The command has many useful arguments; see the online documentation.
split file - Splits a file into several smaller files. The command has many arguments; see the online documentation
sync - Completes all pending input/output operations (requires root privileges).
telnet host - Opens a login session on the specified host.
top - Prints a display of system processes that's continually updated until the user presses the q key.
traceroute host - Uses echo requests to determine and print a network path to the host.
uptime - Prints the system uptime.
w - Prints the current system users.
wall - Prints a message to each user except those who've disabled message reception. Type Ctrl-D to end the message.
An A-Z Index of the Bash command line for Linux.
adduser Add a user to the system
addgroup Add a group to the system
alias Create an alias •
apropos Search Help manual pages (man -k)
apt-get Search for and install software packages (Debian/Ubuntu)
aptitude Search for and install software packages (Debian/Ubuntu)
aspell Spell Checker
awk Find and Replace text, database sort/validate/index
b
basename Strip directory and suffix from filenames
bash GNU Bourne-Again SHell
bc Arbitrary precision calculator language
bg Send to background
break Exit from a loop •
builtin Run a shell builtin
bzip2 Compress or decompress named file(s)
c
cal Display a calendar
case Conditionally perform a command
cat Display the contents of a file
cd Change Directory
cfdisk Partition table manipulator for Linux
chgrp Change group ownership
chmod Change access permissions
chown Change file owner and group
chroot Run a command with a different root directory
chkconfig System services (runlevel)
cksum Print CRC checksum and byte counts
clear Clear terminal screen
cmp Compare two files
comm Compare two sorted files line by line
command Run a command - ignoring shell functions •
continue Resume the next iteration of a loop •
cp Copy one or more files to another location
cron Daemon to execute scheduled commands
crontab Schedule a command to run at a later time
csplit Split a file into context-determined pieces
cut Divide a file into several parts
d
date Display or change the date & time
dc Desk Calculator
dd Convert and copy a file, write disk headers, boot records
ddrescue Data recovery tool
declare Declare variables and give them attributes •
df Display free disk space
diff Display the differences between two files
diff3 Show differences among three files
dig DNS lookup
dir Briefly list directory contents
dircolors Colour setup for `ls'
dirname Convert a full pathname to just a path
dirs Display list of remembered directories
dmesg Print kernel & driver messages
du Estimate file space usage
e
echo Display message on screen •
egrep Search file(s) for lines that match an extended expression
eject Eject removable media
enable Enable and disable builtin shell commands •
env Environment variables
ethtool Ethernet card settings
eval Evaluate several commands/arguments
exec Execute a command
exit Exit the shell
expect Automate arbitrary applications accessed over a terminal
expand Convert tabs to spaces
export Set an environment variable
expr Evaluate expressions
f
false Do nothing, unsuccessfully
fdformat Low-level format a floppy disk
fdisk Partition table manipulator for Linux
fg Send job to foreground
fgrep Search file(s) for lines that match a fixed string
file Determine file type
find Search for files that meet a desired criteria
fmt Reformat paragraph text
fold Wrap text to fit a specified width.
for Expand words, and execute commands
format Format disks or tapes
free Display memory usage
fsck File system consistency check and repair
ftp File Transfer Protocol
function Define Function Macros
fuser Identify/kill the process that is accessing a file
g
gawk Find and Replace text within file(s)
getopts Parse positional parameters
grep Search file(s) for lines that match a given pattern
groups Print group names a user is in
gzip Compress or decompress named file(s)
h
hash Remember the full pathname of a name argument
head Output the first part of file(s)
help Display help for a built-in command •
history Command History
hostname Print or set system name
i
id Print user and group id's
if Conditionally perform a command
ifconfig Configure a network interface
ifdown Stop a network interface
ifup Start a network interface up
import Capture an X server screen and save the image to file
install Copy files and set attributes
j
jobs List active jobs •
join Join lines on a common field
k
kill Stop a process from running
killall Kill processes by name
l
less Display output one screen at a time
let Perform arithmetic on shell variables •
ln Make links between files
local Create variables •
locate Find files
logname Print current login name
logout Exit a login shell •
look Display lines beginning with a given string
lpc Line printer control program
lpr Off line print
lprint Print a file
lprintd Abort a print job
lprintq List the print queue
lprm Remove jobs from the print queue
ls List information about file(s)
lsof List open files
m
make Recompile a group of programs
man Help manual
mkdir Create new folder(s)
mkfifo Make FIFOs (named pipes)
mkisofs Create an hybrid ISO9660/JOLIET/HFS filesystem
mknod Make block or character special files
more Display output one screen at a time
mount Mount a file system
mtools Manipulate MS-DOS files
mtr Network diagnostics (traceroute/ping)
mv Move or rename files or directories
mmv Mass Move and rename (files)
n
netstat Networking information
nice Set the priority of a command or job
nl Number lines and write files
nohup Run a command immune to hangups
notify-send Send desktop notifications
nslookup Query Internet name servers interactively
o
open Open a file in its default application
op Operator access
p
passwd Modify a user password
paste Merge lines of files
pathchk Check file name portability
ping Test a network connection
pkill Stop processes from running
popd Restore the previous value of the current directory
pr Prepare files for printing
printcap Printer capability database
printenv Print environment variables
printf Format and print data •
ps Process status
pushd Save and then change the current directory
pwd Print Working Directory
q
quota Display disk usage and limits
quotacheck Scan a file system for disk usage
quotactl Set disk quotas
r
ram ram disk device
rcp Copy files between two machines
read Read a line from standard input •
readarray Read from stdin into an array variable •
readonly Mark variables/functions as readonly
reboot Reboot the system
rename Rename files
renice Alter priority of running processes
remsync Synchronize remote files via email
return Exit a shell function
rev Reverse lines of a file
rm Remove files
rmdir Remove folder(s)
rsync Remote file copy (Synchronize file trees)
s
screen Multiplex terminal, run remote shells via ssh
scp Secure copy (remote file copy)
sdiff Merge two files interactively
sed Stream Editor
select Accept keyboard input
seq Print numeric sequences
set Manipulate shell variables and functions
sftp Secure File Transfer Program
shift Shift positional parameters
shopt Shell Options
shutdown Shutdown or restart linux
sleep Delay for a specified time
slocate Find files
sort Sort text files
source Run commands from a file `.'
split Split a file into fixed-size pieces
ssh Secure Shell client (remote login program)
strace Trace system calls and signals
su Substitute user identity
sudo Execute a command as another user
sum Print a checksum for a file
suspend Suspend execution of this shell •
symlink Make a new name for a file
sync Synchronize data on disk with memory
t
tail Output the last part of files
tar Tape ARchiver
tee Redirect output to multiple files
test Evaluate a conditional expression
time Measure Program running time
times User and system times
touch Change file timestamps
top List processes running on the system
traceroute Trace Route to Host
trap Run a command when a signal is set(bourne)
tr Translate, squeeze, and/or delete characters
true Do nothing, successfully
tsort Topological sort
tty Print filename of terminal on stdin
type Describe a command •
u
ulimit Limit user resources •
umask Users file creation mask
umount Unmount a device
unalias Remove an alias •
uname Print system information
unexpand Convert spaces to tabs
uniq Uniquify files
units Convert units from one scale to another
unset Remove variable or function names
unshar Unpack shell archive scripts
until Execute commands (until error)
useradd Create new user account
usermod Modify user account
users List users currently logged in
uuencode Encode a binary file
uudecode Decode a file created by uuencode
v
v Verbosely list directory contents (`ls -l -b')
vdir Verbosely list directory contents (`ls -l -b')
vi Text Editor
vmstat Report virtual memory statistics
w
watch Execute/display a program periodically
wc Print byte, word, and line counts
whereis Search the user's $path, man pages and source files for a program
which Search the user's $path for a program file
while Execute commands
who Print all usernames currently logged in
whoami Print the current user id and name (`id -un')
Wget Retrieve web pages or files via HTTP, HTTPS or FTP
write Send a message to another user
x
xargs Execute utility, passing constructed argument list(s)
yes Print a string until interrupted
. Run a command script in the current shell
### Comment / Remark
Beginner
Server Administrator Commands
arp | Command mostly used for checking existing Ethernet connectivity and IP address Most common use: arp This command should be used in conjunction with the ifconfig and route commands. It is mostly useful for me to check a network card and get the IP address quick. Obviously there are many more parameters, but I am trying to share the basics of server administration, not the whole book of commands. |
df | Display filesystem information Most common use: df -h Great way to keep tabs on how much hard disk space you have on each mounted file system. You should also review our other commands like file permissions here. |
du | Display usage Most common use, under a specific directory: du -a Easily and quickly identify the size of files/programs in certain directories. A word of caution is that you should not run this command from the / directory. It will actually display size for every file on the entire Linux harddisk. |
| |
find | Find locations of files/directories quickly across entire filesystem Most common use: find / -name appname -type d -xdev (replace the word appname with the name of a file or application like gimp) This is a very powerful command and is best used when running as root or superuser. The danger is that you will potentially look across every single file on every filesystem, so the syntax is very important. The example shown allows you to search against all directories below / for the appname found in directories but only on the existing filesystem. It may sound complex but the example shown allows you to find a program you may need within seconds! Other uses and more complex but beneficial functions include using the -exec or execute a command. |
ifconfig | Command line tool to configure or check all network cards/interfaces Most common uses: ifconfig and also ifconfig eth0 10.1.1.1 Using the plain ifconfig command will show you the details of all the already configured network cards or interfaces. This is a great way to get a check that your network hardware is working properly. You may also benefit from this review of server configuration. Using the many other options of ifconfig such as the one listed allows you to assign a particular interface a static IP address. I only show an example and not a real world command above. Also review some commands for file permissions here.. Your best bet, if you want to configure your network card using this command is to first read the manual pages. You access them by typing: man ifconfig |
init | Allows you to change the server bootup on a specific runlevel Most common use: init 5 This is a useful command, when for instance a servers fails to identify video type, and ends up dropping to the non-graphical boot-up mode (also called runlevel 3). |
joe or nano | Easy to use command line editors that are often included with the major Linux flavors Most common uses: A real world example for you to get a better sense on how this works: Maybe you are not up to speed on vi, or never learned how to use emacs? On most Linux flavors the text editor named joe or one named nano are available. These basic but easy to use editors are useful for those who need a text editor on the command line but don't know vi or emacs. Although, I do highly recommend that you learn and use Vi and Emacs editors as well. Regardless, you will need to use a command line editor from time to time. You can also use cat and more commands to list contents of files, but this is basic stuff found under the basic linux commands listing. Try: more filename to list contents of the filename. |
netstat | Summary of network connections and status of sockets Most common uses: netstat and also netstat |head and also netstat -r Netstat command simply displays all sockets and server connections. The top few lines are usually most helpful regarding webserver administration. Therefore if you are doing basic webserver work, you can quickly read the top lines of the netstat output by including the |head (pipe and head commands). Using the -r option gives you a very good look at the network routing addresses. This is directly linked to the route command. |
nslookup | Checks the domain name and IP information of a server Most common use: nslookup www.hostname.com You are bound to need this command for one reason or another. When performing server installation and configuration this command gives you the existing root server IP and DNS information and can also provide details from other remote servers. Therefore, it is also a very useful security command where you can lookup DNS information regarding a particular host IP that you may see showing up on your server access logs. Note there are some other commands like file permissions that may also help. There is a lot more to this command and using the man pages will get you the details by typing: man nslookup |
ping | Sends test packets to a specified server to check if it is responding properly Most common use: ping 10.0.0.0 (replace the 10.0.0.0 with a true IP address) This is an extremely useful command that is necessary to test network connectivity and response of servers. It creates a series of test packets of data that are then bounced to the server and back giving an indication whether the server is operating properly. It is the first line of testing if a network failure occurs. If ping works but for instance FTP does not, then chances are that the server is configured correctly, but the FTP daemon or service is not. However, if even ping does not work there is a more significant server connectivity issue& like maybe the wires are not connected or the server is turned off! The outcome of this command is pretty much one of two things. Either it works, or you get the message destination host unreachable. It is a very fast way to check even remote servers. |
ps | Lists all existing processes on the server Most common uses: ps and also ps -A |more The simple command will list every process associated with the specific user running on the server. This is helpful in case you run into problems and need to for instance kill a particular process that is stuck in memory. On the other hand, as a system administrator, I tend to use the -A with the |more option. This will list every process running on the server one screen at a time. Read more of our commands on our reallylinux.com help page. I use ps to quickly check what others are goofing with on my servers and often find that I'm the one doing the dangerous goofing! |
rm | Removes/deletes directories and files Most common use: rm -r name (replace name with your file or directory name) The -r option forces the command to also apply to each subdirectory within the directory. This will work for even non-empty directories. For instance if you are trying to delete the entire contents of the directory x which includes directories y and z this command will do it in one quick process. That is much more useful than trying to use the rmdir command after deleting files! Instead use the rm -r command and you will save time and effort. You may already have known this but since server administrators end up spending a lot of time making and deleting I included this tip! |
route | Lists the routing tables for your server Most common use: route -v This is pretty much the exact same output as the command netstat -r. You can suit yourself which you prefer to run. I tend to type netstat commands a lot more than just route and so it applies less to my situation, but who knows, maybe you are going to love and use route the most! |
shred | Deletes a file securely by overwriting its contents Most common use: shred -v filename (replace filename with your specific file) The -v option is useful since it provides extra view of what exactly the shred tool is doing while you wait. On especially BIG files this could take a bit of time. The result is that your file is so thoroughly deleted it is very unlikely to ever be retrieved again. This is especially useful when trying to zap important server related files that may include confidential information like user names or hidden processes. It is also useful for deleting those hundreds of love notes you get from some of the users on your server, another bonus of being a server administrator. :) |
sudo | The super-user do command that allows you to run specific commands that require root access. Most common use: sudo command (replace command with your specific one) This command is useful when you are logged into a server and attempt a command that requires super-user or root privileges. In most cases, you can simply run the command through sudo, without having to log in as root. In fact, this is a very beneficial way to administer your server without daily use of the root login, which is potentially dangerous. |
top | Displays many system statistics and details regarding active processes Most common use: top This is a very useful system administrator tool that basically gives you a summary view of the system including number of users, memory usage, CPU usage, and active processes. Often during the course of a day when running multiple servers, one of my Xwindows workstations just displays the top command from each of the servers as a very quick check of their status and stability. |
touch | Allows you to change the timestamp on a file. Most common use: touch filename Using the basic touch command, as above, will simply force the current date and time upon the specified file. This is helpful, but not often used. |
traceroute | Traces the existing network routing for a remote or local server Most common use: traceroute hostname (replace hostname with the name of your server such as reallylinux.com) This is a very powerful network command that basically gives the exact route between your machine and a server. In some cases you can actually watch the network hops from country to country across an ocean, through data centers, etc. Read more of our commands on our reallylinux.com help page. This comes in handy when trying to fix a network problem, such as when someone on the network can not get access to your server while others can. This can help identify the break or error along the network line. One strong note to you is not to misuse this command! When you run the traceroute everyone of those systems you see listed also sees YOU doing the traceroute and therefore as a matter of etiquette and respect this command should be used when necessary not for entertainment purposes. A key characteristic of gainfully employed server administrators: knowing when to use commands and when not to use them! |
w | An extension of the who command that displays details of all users currently on the server Most common uses: w This is a very important system admin tool I use commonly to track who is on the server and what processes they are running. It is obviously most useful when run as a superuser. The default setting for the w command is to show the long list of process details. You can also run the command w -s to review a shorter process listing, which is helpful when you have a lot of users on the server doing a lot of things! Remember that this is different than the who command that can only display users not their processes. |
who | Tool used to monitor who is on the system and many other server related characteristics Most common uses: who and also who -q and also who -b The plain command just lists the names of users currently on the server. Using the -q option allows you to quickly view just the total number of users on the system. Using the -b option reminds you how long it has been since you rebooted that stable Linux server! One of my servers had a -b of almost three years! Yes, that's why we at reallylinux.com call it really Linux! |