ManyCodes.com – codes & scripts Get free programming codes and tutorials!

11Jan/120

How to create a symlink in the Linux command console?

 ln -s <destination> <linkname> 

If the desired link filename is the same as the destination's filename, and the current working directory is the desired location for the link, then you only need:

  ln -s <destination> 

A symbolic link (also symlink or soft link) is a special type of file that contains a reference to another file or directory in the form of an absolute or relative path and that affects pathname resolution. Symbolic links were already present by 1978 in mini-computer operating systems from DEC and Data General's RDOS.

Today they are supported by the POSIX operating-system standard, most Unix-like operating systems such as FreeBSD, GNU/Linux, and Mac OS X, and also Windows operating systems such as Windows Vista, Windows 7 and to some degree in Windows 2000 and Windows XP.Symbolic links operate transparently for most operations: programs which read or write to files named by a symbolic link will behave as if operating directly on the target file. However, programs that need to handle symbolic links specially (e.g., backup utilities) may identify and manipulate them directly.

6Jun/111

How to Open rar file or Extract rar files under Linux or UNIX

RAR files are in compressed archive format, if you have downloaded rar files from the Internet, you need to unpack or unrar them (extract rar files).RAR is a proprietary file format for data compression and archiving, developed by Eugene Roshal.Under Linux and UNIX, use command called unrar. By default unrar is not being installed on Linux, FreeBSD or UNIX oses. You can install unrar command with the help of apt-get or yum command.

Install unrar command

Under Debian Linux, you need to type apt-get as follows to install unrar program:
# apt-get install unrar

If you are using Fedora core Linux then use yum command as follows (see discussion below):
# yum install unrar

If you are using FreeBSD, use:
# pkg_add -v -r unrar

If any of above, methods is not working for you, download binary package from official rarlab site:
$ cd /tmp
$ wget http://www.rarlab.com/rar/rarlinux-3.6.0.tar.gz

Untar file
$ tar -zxvf rarlinux-3.6.0.tar.gz

Both unrar and rar commands are located in rar sub-directory. Just go to rar directory:
$ cd rar
$ ./unrar

Now copy rar and unrar to /bin directory:
# cp rar unrar /bin

How to use unrar

unrar command supports various options below are common options that you need to use everyday.

Task: To open rar (unpack) file in current directory type command:

$ unrar e file.rar

Please note that replace file.rar filename with your actual filename.

Task: List (l) file inside rar archive:

$ unrar l file.rar

Task: To extract (x) files with full path type command:

$ unrar x file.rar

(D) To test (t) integrity of archive, file type command:
$ unrar t file.rar

23May/110

How to Copy, move, rename, and remove files in Linux

< Copying >

To copy files, you use the cp command. The following will copy file to file2. Note that if file2 doesn't exist, it'll be created, but if it exists, it'll be overwritten:
$ cp file file2

There aren't any undo commands in the Linux CLI, so accidentally overwriting an important file would probably make you pull your head off. The risk of doing so is smaller if you use the -i option ("interactive") with cp. The following does the same as the above, but if file2 exists, you'll be prompted before overwriting:

$ cp -i file file2
cp: overwrite `file2'? n
$

So it's a good idea to use the -i option whenever you're dealing with important files you don't want to lose!

If you want to copy file into directory dir1:
$ cp file dir1

The following would do the same as the above, copy file into dir1, but under a different name:
$ cp file dir1/file2

You can also copy multiple files into one directory with a single command:
$ cp file1 file2 file3 dir1

Note that if the last argument isn't a directory name, you'll get an error message complaining about it.

 

< Moving and renaming >

The mv command can be used for moving or renaming files. To rename a file, you can use it like this:
$ mv file file2

If file2 doesn't exist, it'll be created, but if it exists, it'll be overwritten. If you want to be prompted before overwriting files, you can use the -i option the same way as with cp:

$ mv -i file file2
mv: overwrite `file2'? y
$

To move the file into another directory:
$ mv file dir1

If you want to rename the file to file2 and move it into another directory, you probably already figured out the command:
$ mv file dir1/file2

 

< Removing files >

The rm command is used for removing files and directories. To remove a file:
$ rm file

If you use the -i option, you'll be prompted before removing the file:
$ rm -i file

You can also delete more files at once:
rm file1 file2

Be careful with the rm command! As I already told you, Linux doesn't have any undo commands, and it doesn't put files into Trash where you can save them later. Once you've deleted a file.

Ubuntu, fedora, centos, linux

27Sep/100

How to Use C’s volatile Keyword

The proper use of C's volatile keyword is poorly understood by many programmers. This is not surprising, as most C texts dismiss it in a sentence or two. This article will teach you the proper way to do it.

Have you experienced any of the following in your C or C++ embedded code?

  • Code that works fine--until you enable compiler optimizations
  • Code that works fine--until interrupts are enabled
  • Flaky hardware drivers
  • RTOS tasks that work fine in isolation--until some other task is spawned

If you answered yes to any of the above, it's likely that you didn't use the C keyword volatile. You aren't alone. The use of volatile is poorly understood by many programmers. Unfortunately, most books about the C programming language dismiss volatile in a sentence or two.

C's volatile keyword is a qualifier that is applied to a variable when it is declared. It tells the compiler that the value of the variable may change at any time--without any action being taken by the code the compiler finds nearby. The implications of this are quite serious. However, before we examine them, let's take a look at the syntax.

volatile keyword syntax

To declare a variable volatile, include the keyword volatile before or after the data type in the variable definition. For instance both of these declarations will declare foo to be a volatile integer:

volatile int foo;
int volatile foo;

Now, it turns out that pointers to volatile variables are very common, especially with memory-mapped I/O registers. Both of these declarations declare pReg to be a pointer to a volatile unsigned 8-bit integer:

volatile uint8_t * pReg;
uint8_t volatile * pReg;

Volatile pointers to non-volatile data are very rare (I think I've used them once), but I'd better go ahead and give you the syntax:

int * volatile p;

And just for completeness, if you really must have a volatile pointer to a volatile variable, you'd write:

int volatile * volatile p;

Incidentally, for a great explanation of why you have a choice of where to place volatile and why you should place it after the data type (for example, int volatile * foo), read Dan Sak's column "Top-Level cv-Qualifiers in Function Parameters" (Embedded Systems Programming, February 2000, p. 63).

Finally, if you apply volatile to a struct or union, the entire contents of the struct/union are volatile. If you don't want this behavior, you can apply the volatile qualifier to the individual members of the struct/union.

Proper use of volatile

A variable should be declared volatile whenever its value could change unexpectedly. In practice, only three types of variables could change:

1. Memory-mapped peripheral registers

2. Global variables modified by an interrupt service routine

3. Global variables accessed by multiple tasks within a multi-threaded application

We'll talk about each of these cases in the sections that follow.

Peripheral registers

Embedded systems contain real hardware, usually with sophisticated peripherals. These peripherals contain registers whose values may change asynchronously to the program flow. As a very simple example, consider an 8-bit status register that is memory mapped at address 0x1234. It is required that you poll the status register until it becomes non-zero. The naive and incorrect implementation is as follows:

uint8_t * pReg = (uint8_t *) 0x1234;

// Wait for register to become non-zero
while (*pReg == 0) { } // Do something else

This will almost certainly fail as soon as you turn compiler optimization on, since the compiler will generate assembly language that looks something like this:

mov ptr, #0x1234 mov a, @ptr

loop:
bz loop

The rationale of the optimizer is quite simple: having already read the variable's value into the accumulator (on the second line of assembly), there is no need to reread it, since the value will always be the same. Thus, in the third line, we end up with an infinite loop. To force the compiler to do what we want, we modify the declaration to:

uint8_t volatile * pReg = (uint8_t volatile *) 0x1234;

The assembly language now looks like this:

mov ptr, #0x1234

loop:
mov a, @ptr
bz loop

The desired behavior is achieved.

Subtler problems tend to arise with registers that have special properties. For instance, a lot of peripherals contain registers that are cleared simply by reading them. Extra (or fewer) reads than you are intending can cause quite unexpected results in these cases.

Interrupt service routines

Interrupt service routines often set variables that are tested in mainline code. For example, a serial port interrupt may test each received character to see if it is an ETX character (presumably signifying the end of a message). If the character is an ETX, the ISR might set a global flag. An incorrect implementation of this might be:

int etx_rcvd = FALSE;

void main()
{
...
while (!ext_rcvd)
{
// Wait
}
...
}

interrupt void rx_isr(void)
{
...
if (ETX == rx_char)
{
etx_rcvd = TRUE;
}
...
}

With compiler optimization turned off, this code might work. However, any half decent optimizer will "break" the code. The problem is that the compiler has no idea that etx_rcvd can be changed within an ISR. As far as the compiler is concerned, the expression !ext_rcvd is always true, and, therefore, you can never exit the while loop. Consequently, all the code after the while loop may simply be removed by the optimizer. If you are lucky, your compiler will warn you about this. If you are unlucky (or you haven't yet learned to take compiler warnings seriously), your code will fail miserably. Naturally, the blame will be placed on a "lousy optimizer."

The solution is to declare the variable etx_rcvd to be volatile. Then all of your problems (well, some of them anyway) will disappear.

Multi-threaded applications

Despite the presence of queues, pipes, and other scheduler-aware communications mechanisms in real-time operating systems, it is still fairly common for two tasks to exchange information via a shared memory location (that is, a global). Even as you add a preemptive scheduler to your code, your compiler has no idea what a context switch is or when one might occur. Thus, another task modifying a shared global is conceptually identical to the problem of interrupt service routines discussed previously. So all shared global variables should be declared volatile. For example, this is asking for trouble:

int cntr;

void task1(void)
{
cntr = 0;

while (cntr == 0)
{
sleep(1);
}
...
}

void task2(void)
{
...
cntr++;
sleep(10);
...
}

This code will likely fail once the compiler's optimizer is enabled. Declaring cntr to be volatile is the proper way to solve the problem.

Final thoughts

Some compilers allow you to implicitly declare all variables as volatile. Resist this temptation, since it is essentially a substitute for thought. It also leads to potentially less efficient code.

Also, resist the temptation to blame the optimizer or turn it off. Modern optimizers are so good that I cannot remember the last time I came across an optimization bug. In contrast, I come across failures by programmers to use volatile with depressing frequency.

If you are given a piece of flaky code to "fix," perform a grep for volatile. If grep comes up empty, the examples given here are probably good places to start looking for problems.

Reference:

Jones, Nigel. "Introduction to the Volatile Keyword" Embedded Systems Programming, July 2001

25Aug/090

How to determine which sevices are enabled at boot time in linux

How do I find out which services are enabled at Boot under Ubuntu/CentOS/RHEL/Fedora Linux? How can I disable a service which is not needed or I dont want to run every time the linux machine starts?

Open terminal and login as root user.

Type the following command to list all services which are enabled at boot:

#chkconfig --list | grep $(runlevel  | awk '{ print $2}'):on

Sample output:

acpid          	0:off	1:off	2:off	3:on	4:on	5:on	6:off
anacron        	0:off	1:off	2:on	3:on	4:on	5:on	6:off
atd            	0:off	1:off	2:off	3:on	4:on	5:on	6:off
auditd         	0:off	1:off	2:on	3:on	4:on	5:on	6:off
cpuspeed       	0:off	1:on	2:on	3:on	4:on	5:on	6:off
crond          	0:off	1:off	2:on	3:on	4:on	5:on	6:off
dkms_autoinstaller	0:off	1:off	2:on	3:on	4:on	5:on	6:off
haldaemon      	0:off	1:off	2:off	3:on	4:on	5:on	6:off
hidd           	0:off	1:off	2:on	3:on	4:on	5:on	6:off
irqbalance     	0:off	1:off	2:on	3:on	4:on	5:on	6:off
kudzu          	0:off	1:off	2:off	3:on	4:on	5:on	6:off
lighttpd       	0:off	1:off	2:on	3:on	4:on	5:on	6:off
lm_sensors     	0:off	1:off	2:on	3:on	4:on	5:on	6:off
lvm2-monitor   	0:off	1:on	2:on	3:on	4:on	5:on	6:off
mcstrans       	0:off	1:off	2:on	3:on	4:on	5:on	6:off
mdmonitor      	0:off	1:off	2:on	3:on	4:on	5:on	6:off
messagebus     	0:off	1:off	2:off	3:on	4:on	5:on	6:off
microcode_ctl  	0:off	1:off	2:on	3:on	4:on	5:on	6:off
mysqld         	0:off	1:off	2:on	3:on	4:on	5:on	6:off
named          	0:off	1:off	2:on	3:on	4:on	5:on	6:off
netfs          	0:off	1:off	2:off	3:on	4:on	5:on	6:off
network        	0:off	1:off	2:on	3:on	4:on	5:on	6:off
ntpd           	0:off	1:off	2:on	3:on	4:on	5:on	6:off
pcscd          	0:off	1:off	2:on	3:on	4:on	5:on	6:off
psacct         	0:off	1:off	2:on	3:on	4:on	5:on	6:off
readahead_early	0:off	1:off	2:on	3:on	4:on	5:on	6:off
restorecond    	0:off	1:off	2:on	3:on	4:on	5:on	6:off
rhnsd          	0:off	1:off	2:on	3:on	4:on	5:on	6:off
rpcgssd        	0:off	1:off	2:off	3:on	4:on	5:on	6:off
rpcidmapd      	0:off	1:off	2:off	3:on	4:on	5:on	6:off
sendmail       	0:off	1:off	2:on	3:on	4:on	5:on	6:off
setroubleshoot 	0:off	1:off	2:off	3:on	4:on	5:on	6:off
smartd         	0:off	1:off	2:on	3:on	4:on	5:on	6:off
snmpd          	0:off	1:off	2:on	3:on	4:on	5:on	6:off
xfs            	0:off	1:off	2:on	3:on	4:on	5:on	6:off
xinetd         	0:off	1:off	2:off	3:on	4:on	5:on	6:off
yum-updatesd   	0:off	1:off	2:on	3:on	4:on	5:on	6:off

The first column of above output is the name of a service which is currently enabled at boot. You need to review each service.

Task: Disable services

To stop service, enter:

# service {service-name} stop
 # service vmware stop

To disable service, enter:

# chkconfig {service-name} off
 # chkconfig vmware off

You may also use ntsysv command to manage all services.

A note about outdated insecure service

All of the following services must be disabled to improve server security:

  1. Inetd and Xinetd (inetd xinetd) - Use direct services configured via SysV and daemons.
  2. Telnet (telnet-server) - Use ssh
  3. Rlogin, Rsh, and Rcp ( rsh-server ) - Use ssh and scp.
  4. NIS (ypserv) : Use OpenLDAP or Fedora directory server.
  5. TFTP (tftp-server) : Use SFTP or SSH.

To delete all of the service enter:

# yum erase inetd xinetd ypserv tftp-server telnet-server rsh-serve
25Aug/090

How to view or display a logfile in real time on screen in linux

How do I see the log file in real time including all incoming logs as well?

You can use the tail command in linux command line which outputs the last part of files in real time including all incoming logs to a file. So you can view the last parts of your logs file (like access logs for the server) using this in real time!

Note: you may need to login as root user to view log files.

Command

tail -f file-name command

If your log file name is /var/log/lighttpd/access.log, enter:

tail -f /var/log/lighttpd/access.log

If your php log file name is /var/log/lighttpd/scripts.log, enter

tail -f /var/log/lighttpd/scripts.log

You will get a scrolling view of the /var/log/lighttpd/scripts.log for all incoming entries on screen. To stop simply hit CTRL+C.

10Aug/090

How to Stop/Restart Lighttpd Web Server in Debian / Ubuntu / FreeBSD linux

/etc/init.d/lighttpd is a script under Linux to stop / restart lighttpd web server.

To stop lighttpd:

Use the following command to stop lighttpd:

# /etc/init.d/lighttpd stop

To restart lighttpd:

Just type the following command to restart lighttpd:

# /etc/init.d/lighttpd restart

To start lighttpd:

# /etc/init.d/lighttpd start

Debian / Ubuntu Linux Start lighttpd

# /etc/init.d/lighttpd start

Debian / Ubuntu Linux - Stop lighttpd

# /etc/init.d/lighttpd stop

Debian / Ubuntu Linux - Restart lighttpd

# /etc/init.d/lighttpd restart

FreeBSD Start lighttpd web server

# /usr/local/etc/rc.d/lighttpd start

FreeBSD - Stop lighttpd webserver

# /usr/local/etc/rc.d/lighttpd stop

FreeBSD - Restart lighttpd webserver

# /usr/local/etc/rc.d/lighttpd restart

In case if you don't have init script, type the following:

# killall lighttpd
10Aug/090

How to install webmin on your Linux web server (Redhat Fedora Caldera Mandrake SuSE MSC)

Installing webmin on your linux webserver is easy. With webmin, you can use ispconfig which is a web hosting script that you can use to host many website in one server.
Webmin website: http://www.webmin.com/

Since I have fedora I can install like this:
(this tutorial is suitable for Redhat, SuSE, Caldera, Mandrake or MSC Linux, 13M)

Login to your shell, i will be using ssh so i send this command:

wget http://prdownloads.sourceforge.net/webadmin/webmin-1.350-1.noarch.rpm

Once it has finished downloadin i send this command:

rpm -U webmin-1.350-1.noarch.rpm

(make sure to use upper case U above)

The rest of the install will be done automatically to the directory /usr/libexec/webmin, the administration username set to root and the password to your current root password. You should now be able to login to Webmin at the URL http://localhost:10000/ .

Webmin install complete. You can now login to https://hostname.domain:10000/
as root with your root password.

NOTE: the default login and password is your root and root password. this is the same login you used with you ssh to your server or whatever your root password is, so your login will be like this:

Username: root
Password: xxxx (what ever your root password is)

6Aug/091

How to Create a Cydia Repository for the iphone

A Cydia Repository which is much like an Installer source, is also a way to host your own files, like applications, themes, and wallpapers on Cydia. Cydia is the unofficial application distribution app for jailbroken iPhones and iPod touches for applications that could not make it to the official app store managed and run by apple.

Now this is a guide on creating your own repository for cydia, and no, you don't need a website of your own to do it! Note that while the screenshots within this guide were taken on a Mac, you can easily follow this tutorial with Debian (see "What's Needed if you have no idea what the heck I'm talking about).

Important: There are steps in the guide where I'll instruct you to copy text from this page into a Text Editor and into Terminal. Unfortunately, due to this forum's restrictions on the number of images allowed within a post (6), I had to convert about 90% of the guide into one big image, so you'll have to manually type the text in. Sorry about that.

Also, you may have already seen that this guide is pretty long. Don't get scared and decide not to try; it's only long because I wanted to make it as detailed as possible. Doing this is not as hard as it looks.

First off, check out the EverythingiCafe Cydia Repository before you create your own. If all you want is a place to host your files, we'll host your stuff for you. If you want your own repository, carry on.

What's Needed
• Internet Access
• Basic Text Editor
• Either a Virtual Machine with Debian installed, a computer
running Debian, or a Mac with Fink installed.
• Either a website of your own or a free sub-domain with FTP access (Your own website is recommended, but if you're going to use the latter of the two, I suggest using 110mb.com.)

Here is tutorial for how to create a cydia repository for iphone: http://kttns.org/nmuym

6Aug/090

How to Run as Administrator in Vista Command Line?

Recently I wanted to do some actions in Windows Vista command line prompt but with elevated access as an Administrator. You may need this access to do actions like creating symbolic links etc.

So, how to run as administrator in Vista command line?

The easiest way is to use the type cmd in the Vista Start Run box and use the keyboard shortcut Ctrl + Shift + Enter instead of just pressing Enter. This will open the Command Prompt in Administrator mode.

cmd in Vista

You can also right click cmd.exe and click Run as Administrator.

cmd as administrator in Vista

Command Prompt with Administrator access in Windows Vista.

Run Vista Command Prompt as Adminstrator

On the other hand, you can also activate Administrator account in Vista, so that you can login from welcome screen.