13
Last Revised: 1/22/2013 1 EE355 Name: Getting Started Preparation for next class: Watch instructor video modules regarding C/C++ Introduction Watch instructor video modules regarding Control Structures Perform: D.S. Malik Chapter 2 Homework on Blackboard D.S. Malik Chapter 4 and 5 Homework on Blackboard Complete the Linux tutorial (see online version of this document)

EE355 Name: Getting Started - USC Ming Hsieh Department of

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

Page 1: EE355 Name: Getting Started - USC Ming Hsieh Department of

Last Revised: 1/22/2013 1

EE355 Name:

Getting Started Preparation for next class:

Watch instructor video modules regarding C/C++ Introduction

Watch instructor video modules regarding Control Structures

Perform:

D.S. Malik Chapter 2 Homework on Blackboard

D.S. Malik Chapter 4 and 5 Homework on Blackboard

Complete the Linux tutorial (see online version of this document)

Page 2: EE355 Name: Getting Started - USC Ming Hsieh Department of

EE 355 Linux Tutorial - Linux Tutorial

2 Last Revised: 1/22/2013

EE 355 Linux Tutorial - Linux Tutorial

1 Introduction In this lab you will login to your Linux VM and write your first C/C++ program, compile it, and then execute it.

2 What you will learn In this lab you will learn the basic commands and navigation of Linux/Unix, its file system, the GNU C/C++ compiler and a few basic applications such as Gedit. Important: The Linux operating system and environment shares a vast majority of commands and methods with Unix.

3 Background Information and Notes

3.1 Software to Install on your PC Start by download Oracle VirtualBox. This allows your machine and current OS to run a Linux OS "virtually" (i.e. the Linux OS thinks it has control of the full machine even though it really doesn't). Go to: https://www.virtualbox.org/wiki/Downloads Click the 'x86/amd64' link next to your chosen OS' (Windows or OS X), download the install file, run it, and choose all the default options. Be sure to allow all the USB, network, and other OS drivers to be installed. Next, download the Ubuntu VM image (Ubuntu is a popular OS flavor of Linux ), unzip it, and move it to a folder of your choice and note that folder. http://ee-classes.usc.edu/cs101/ee355-vm.ova Below is a list of recommended software you should install that will be helpful over multiple courses in CS and EE. These tools allow you to access remote servers, run GUI apps on those servers, and transfer files between your PC and those servers. For Windows:

FileZilla FTP – Available from : https://software.usc.edu/index.aspx

XWin-32 – Available from : https://software.usc.edu/index.aspx

PuTTY – Available from : https://software.usc.edu/index.aspx

(Optional) Ultra VNC Viewer - http://www.uvnc.com/download/1082/1082full.html

Page 3: EE355 Name: Getting Started - USC Ming Hsieh Department of

EE 355 Linux Tutorial - Linux Tutorial

Last Revised: 1/22/2013 3

For Mac:

X Server: http://developer.apple.com/opensource/tools/runningx11.html

Fetch FTP – Available from : https://software.usc.edu/index.aspx

(Optional) Chicken of the VNC Viewer: http://sourceforge.net/projects/cotvnc/files/cotvnc/Chicken%20of%20the%20VNC%202.0b4/cotvnc-20b4.dmg/download

Reference:

http://www.usc.edu/its/unix/

3.2 Getting Started with Unix1 and Accessing your Account Solaris vs. Unix vs. Linux UNIX was developed by AT&T Bell Labs in 1969. Later, a research group at University of California at Berkley added some very important modules to the basic “kernel” of UNIX. This version of Unix is usually referred to as the Berkley Unix. It was here that Unix really took off as the operating system of choice for developers who wanted to add functionality to the kernel so as to fit their needs. Several companies took the Unix kernel and added various features to it to suit their machines and target market. Solaris is the operating system distributed by Sun Microsystems which uses the Unix kernel. The differences between Unix and Linux, however, are more subtle and therefore, arguable. Google the phrase “differences between Unix and Linux” if you really care to find out. From a novice user’s standpoint, there are really no differences. Almost all basic Unix commands work on Linux.

4 Procedure and Reference

4.1 Starting your VM Please reference the following video that will walk you through launching your Ubuntu Linux VM and starting to use it. Below is a small text summary. http://ee.usc.edu/~redekopp/Streaming/ee355_ubuntu_vm/ee355_ubuntu_vm.html

Launch VirtualBox from your host OS. From the VirtualBox Menu choose File..Import. Then navigate to the folder where you downloaded your Ubuntu VM Image and enter that folder. You should see a file with the .ova extension. Choose this file.

1 Acknowledgement: Much of the material covered in this handout is taken from a tutorial produced by

Bilal Zafar and user guides prepared by the Information Technology Services at the University of Southern California. Please visit www.usc.edu/its/software for more details on the topics covered.

Page 4: EE355 Name: Getting Started - USC Ming Hsieh Department of

EE 355 Linux Tutorial - Linux Tutorial

4 Last Revised: 1/22/2013

Note: In Virtual Machine terminology we refer to the 'host' OS which is the actual OS your PC is running (OS X or Windows) and the 'guest' OS which is the OS running virtually (i.e. Ubuntu).

Back in the Virtual Box Manager, click on the Ubuntu Image and click 'Start'. Say 'Ok' or 'Yes' to any information messages about 'Auto capture …' and you can check the box to not show those messages again. If the VM successfully launches you should arrive at a login screen with the user 'Student' highlighted. Your username is: student Your password is: memory Double-click the Student account and enter your password. You can now use your VM by launching a Terminal and entering commands. Continue through the rest of this lab to learn the basic Linux commands and file structure.

4.2 Unix File System and Navigation Commands It is important to understand how directories are arranged in Unix/Linux. Logically, Unix files are organized in a tree-like structure (just like in Windows). '/' is the root directory (much like C: is for Windows). Underneath root are other directories/folders with a sample structure shown below:

Figure 1- Unix/Linux File System Structure

/

home usr etc

student bluetooth

pa2 examplespa1

robot fileio

Shortcuts:

.. = parent directory (up one level)

. = current directory

~ = home directory (/home/student)

/ = root directory

Page 5: EE355 Name: Getting Started - USC Ming Hsieh Department of

EE 355 Linux Tutorial - Linux Tutorial

Last Revised: 1/22/2013 5

Everyone's account (and associated files) is stored under their home directory

(usually their USC username on shared servers such as aludra.usc.edu or parallel05.usc.edu; your username is student on Ubuntu VM's) and is located under /home (e.g. /home/student). Your home directory is where you start when you log into the system. Most Unix applications are located under /usr directory. /etc contains system configuration info and scripts that only the administrator of the system is allowed to change.

The cd command is used to navigate between directories. Change directory to any other sub-directory in your home directory (mail, for example) by entering the command:

cd <directoryname>

To return to the home directory from ANY directory, just type “cd” (without

any options or arguments) or “cd ~” as the ~ is an alias for your home directory.

To go to etc directory (from your home directory), type: cd /etc

In Linux we often want to specify the location of a file relative to the current directory. To help, the current directory can always be referenced by “.”, the directory one level above the current is referenced by “..” whereas the home directory is referenced by “~”. For example, suppose you were in the directory home/student/examples/fileio and you wanted to go up to the

“examples” directory you would type: "cd ..". If you wanted to go

directly to the home directory, you could type "cd ../.." to go up two directories but it would be easier to just type: "cd ~" (the shortcut for your

home directory). To go from the robot directory to pa1 you could type "cd ../../pa1".

List (ls) is perhaps the most commonly used Unix command. It displays (lists) the files within a directory as well as any subdirectories. Let’s give it a try.

Type: ls

at the prompt. Notice that we did not use any options or arguments and the system returned a simple list of all the files and folders in the current directory. Let us tweak this command with some options.

Type: ls –a

at the prompt. Is the list of directory contents returned by "ls –a" longer than the one returned by just "ls"? Did you notice some files starting with “.” reported

by "ls –a"? This is because the option –a asks forces the system to return ALL files, including system files and hidden files, to be displayed. Now, let’s try another flavor of the same command.

Page 6: EE355 Name: Getting Started - USC Ming Hsieh Department of

EE 355 Linux Tutorial - Linux Tutorial

6 Last Revised: 1/22/2013

Type: ls -la

What additional information is produced by "ls –l"?

We can specify more than one option for most commands. For example, the

option “-t” sorts the list by time. Let us combine this with the “-l” option.

Type: ls –lt

Notice the dates corresponding to the files and directories reported. We can also give a folder as argument to the list command to view the contents of that directory rather than the current directory. Look for a directory in your home directory and use the command syntax

ls –lt <directory name>

to see its contents. We will look at several other Unix commands and utilities later in this lab. Files and directories in Unix/Linux have “permissions”. There are three levels of permissions: user, group, and all (world). User permissions set the access to a file for you and your account. Group permissions apply to other users in your group (usually all students in the course). All or world permissions apply to any user of the system. Within each level you can set the read, write, and executable permissions. To view the permissions, simply type "ls –l". At the beginning of each line will be listing of the user, group, and all permissions in that order. A dash means the permission is not set while the letter ‘r’, ‘w’, or ‘x’ indicates the permission is set. Most data files will only be readable and writable from your user level (no one else should be able to see or modify your files). Executable files (including all directories) should be marked with the user executable permission to allow you to run them (or enter them in the case of directories). In some cases you may need to change the permissions of a file. For example, when setting up your student web page, you want the world (all) to have permission to read your files. In this case you may set the permission to allow all to read and execute the page but not write your files. The chmod program will be used for this and is explained later. Text Editors Most Unix/Linux systems provide several text editors. vi (short for “visual editor”), nano, gedit and emacs are the most common editors. ‘gedit’ is perhaps the most user-friendly of these three editors while ‘Emacs’ is the most powerful. Gedit and emacs are GUI-based. 'nano' is a simple non-GUI text editor..

Gedit: In gedit, you can open multiple files simultaneously and switch between them with ease. Each of these files is opened in a separate tab and you can switch between them.

Page 7: EE355 Name: Getting Started - USC Ming Hsieh Department of

EE 355 Linux Tutorial - Linux Tutorial

Last Revised: 1/22/2013 7

To open or create a new file, simply type “gedit <file_name> &” at the prompt. “&” at the end of the command is optional though recommended. It can be added to the end of any command but is usually only applied to commands that will launch new windows. The ‘&’ tells the shell to simply fork off the new process and let it run simultaneously with the current shell. Without the ‘&’ the command shell would hang, waiting for you to finish using and then exit the newly started application. This will prevent you from entering any more commands at the prompt until the application is closed. You can try this by typing: “gedit welcome.txt &” and enter a simple text message like “Hello and welcome to EE355.”, save the file, and exit.

4.3 UNIX Commands In general, a Linux command usually has three components:

command -[options] <arguments>

“Command” refers to the actual keyword or executable which is interpreted by the shell, “options” control the behavior of the command, and “arguments” are entities the command is applied to (files or directories, usually). The syntax rules indicate that the command, options and arguments must be separated by spaces and a minus (or hyphen) sign should precede the options. Looking back at the “ls” command, we see all three at work. Entering “ls –l ~” at the Unix prompt specifies the command as “ls”, the option as “-l” which shows the long format (more details) of the files and the argument “~” indicates the directory to list (in this case, your home directory). Below are some basic Unix commands along with some of the options that are available for each of them. Directory Management:

Command Example Description

mkdir mkdir test Creates a directory called ‘test’ under the current directory

cd cd test Change to directory named test from the current directory (test should be a sub-directory of the current directory)

pwd pwd Show current working directory

ls ls –l List contents of current directory

clear clear Clears your terminal screen if possible

rmdir rmdir test Removes an empty directory called test

Page 8: EE355 Name: Getting Started - USC Ming Hsieh Department of

EE 355 Linux Tutorial - Linux Tutorial

8 Last Revised: 1/22/2013

File management:

Command Example Description

cp cp test.cpp .. Copy the file test.cpp from current directory to the parent directory

mv mv test.cpp ~/pa1 Move test.cpp to directory called pa1 under your home folder.

rm rm ~/pa1/test.cpp Delete the file test.cpp in the directory ~/pa1

chmod chmod +x script.sh Make the file script.sh an executable file

rm –r rm –r ~/pa1 Recursively remove all files and sub-directories inside the directory ~/pa1

grep grep main test.cpp Searches test.cpp for the word "main"

Advanced UNIX Commands and Utilities grep: grep searches an entire file for the pattern you want and displays its findings. If you wanted to search for which files in your current directory contained the word "table" you could enter the command: grep table *

Note: * in Linux/Unix is a "wildcard" character that indicates all files in the directory.

Interestingly, you can use this command to search for a pattern in the results of another command. For example, if you were looking for all the files starting with the keyword “ee355”, you can concatenate the grep command with the ls command we saw earlier. You would type the command: ls –l | grep ee355

Notice the symbol “|” (called “pipe”) between the two commands (“ls” and “grep”). Pipe is used to concatenate commands in Unix. You can use the grep command to print all the instances of a particular keyword in a file.

more: The more utility displays the contents of a text file on the screen, one screenful at a time. It is a handy tool to see a file without opening a text editor. For example, you can see the file you created “welcome.txt” using the more utility by typing: more welcome.txt

Again, you can concatenate the more utility with commands like “ls” to display only one full screen at a time (in case you have too many files/directories). The syntax for that would be:

Page 9: EE355 Name: Getting Started - USC Ming Hsieh Department of

EE 355 Linux Tutorial - Linux Tutorial

Last Revised: 1/22/2013 9

ls –l | more

ps: The ps command lists all the processes currently running. This allows you to explicitly kill a program that might have lost control or crashed. Since you can have multiple sessions running on aludra and nunki simultaneously, and just “ps” gives you a list of processes running under the current session, we recommend the following switches: ps aux |grep <username>

Basically, ps –aux gives a list of ALL the processes running on the machines. Since many users are logged on and you really don’t care about the processes launched by other users, you “grep” that processes owned by you out of that very long list. Here’s a sample output of this command: student@student-desktop:~$ ps aux | grep student student 16219 0.1 0.0 9232 3160 ? S 11:13:44 0:00

/usr/lsd/openssh/d

student 16225 0.0 0.0 2864 2312 pts/111 S 11:13:45 0:00 –bash…

The numbers in the second column are the process IDs. We will use the process ID of a process to kill it. UNIX has its low points! Yes, at times you might find an application (like Emacs) crashing on you. However, you can kill the process very efficiently. As we mentioned before, we use the process ID to kill a process. The command is: kill <process ID>

5 Prelab None

6 Procedure We will now use the commands and knowledge discussed above to write and compile your first C++ program.

6.1 Writing your First Program Start your Ubuntu VM if it is not already. Exercise: Write, compile, and run your first C program.

Page 10: EE355 Name: Getting Started - USC Ming Hsieh Department of

EE 355 Linux Tutorial - Linux Tutorial

10 Last Revised: 1/22/2013

We have created a 'ee355' directory in your home directory. Ensure you see it by listing the contents of your home folder. Note: the ‘$’ represents the command prompt in the commands below. Type what is shown after the ‘$’. $ ls

Now create and navigate into the ee355 folder using the 'mkdir' & ‘cd’ command: $ mkdir ee355

$ cd ee355

While the command prompt on the screen should show you what directory you are in, you also see your current directory path by typing the following: $ pwd

‘pwd’ stands for ‘present working directory’ and will print out your current location. Rather than typing that all the time it may be beneficial to see what directory you are in displayed along with every command prompt. If you want to return to your home directory, we can go “up” one level to the parent directory using ‘..’ [Note the current directory can be referenced using a single dot, ‘.’]. Execute the commands Let us write our first C++ program. We will need to create and edit a text file that contains our source code. $ gedit hello.cpp &

Recall that previously when gedit was running the command prompt froze until we exited gedit. This time when we start gedit we added the ‘&’ at the end. This tells the shell/command prompt to ‘fork’ off the new application and continue accepting commands. In the gedit window type in the following program, verbatim.

#include <iostream>

using namespace std;

int main(int argc, char *argv[])

{

if(argc < 2){

cout << argv[0] << " expects a string to be entered"

cout << " on the command line" << endl;

return 1;

}

cout << "Hello " << argv[1] << ". Welcome to EE355" << endl

return 0;

}

Save the file (File..Save) and go back to the command window leaving gedit open so we can fix any errors if they exist. We now need to compile this program before we can run it. At the command prompt type:

Page 11: EE355 Name: Getting Started - USC Ming Hsieh Department of

EE 355 Linux Tutorial - Linux Tutorial

Last Revised: 1/22/2013 11

$ g++ hello.cpp

Notice an error is output from the compiler that a ‘;’ is expected before ‘return’. That is because valid C statements end with a semicolon ‘;’. Add the semicolon at the end of the cout << “Hello…” statement. Save the file and repeat the compilation command (‘g++ hello.cpp’). Now list the directory contents: $ ls

You should see a file named “a.out” in the directory. This is the default name of the executable created from the compiler. We would prefer a more descriptive name. Let us remove this file. $ rm a.out

Confirm the deletion. Now re-run the compiler and this time we will add an option to indicate the name of the executable file. $ g++ –o hello hello.cpp

Now list the directory contents and ensure there is a hello executable file. Execute the program by typing. [Note: you need to precede the executable name by indicating it is in the current directory by typing ‘./’ $ ./hello

You should notice that it complains that a string is expected. This is as indicated in our program, which wants the user to type in a string (in this case our name) on the command line after the executable file. Re-try the program with the following command $ ./hello TTrojan

You should now see the expected output: “Hello TTrojan. Welcome to EE355.” We can now close gedit since we are done editing the C program. We have successfully created, compiled, and ran our program. It is recommended to keep your files organized nicely. Rather than cluttering up our ‘ee355’ folder, let us create an ‘examples’ directory underneath ‘ee355’ to put example code like this. Create the ‘examples’ directory: $ mkdir examples

Now let’s copy our files from the ‘ee355 folder’ to the ‘examples’ subfolder. For this task we will use the ‘cp’ command which expects some number of source files followed by the destination folder to which the copies should be placed. $ cp hello* examples/

Page 12: EE355 Name: Getting Started - USC Ming Hsieh Department of

EE 355 Linux Tutorial - Linux Tutorial

12 Last Revised: 1/22/2013

The ‘*’ is called a ‘wildcard’ operator and will match any files that start with hello and end with anything else. List the contents of the examples directory. We could do this by typing the full command ‘ls examples’ but we can also use the shell’s built-in features such as path/file completion. If we type the first part of a directory or file name and then hit TAB it will find a matching file and complete the name for you. Try this by typing: $ ls ex (now hit the TAB key and watch what happens)

When you hit TAB it should have completed the ‘examples/’ subdirectory. Note how we do not always have to just list the current directory but can tell ‘ls’ which directory we want to list. If we list the current directory we see that ‘cp’ has truly copied the files (i.e. there is one copy in the ‘ee355’ directory where we created them and copies in the ‘examples’ directory. We could have just moved them if we had wanted. Let us try this: $ mv hello* examples/

Confirm the hello files no longer exist in the current directory. $ ls

Go into the examples directory and make sure the files are there. $ cd examples

$ ls

One last exercise is to use a utility program called 'make' which automatically compile simple C program and can be further scripted for more complex compilations. Delete the 'hello' executable then invoke make: $ rm hello

$ make hello

The name you give after 'make' will be used to try to find a C++ file to compile. 'make' will automatically take that word and add ".cpp" to it and compile that file and create an executable with the name you provided. List the directory to ensure 'hello' exists then run it to ensure it works as expected: $ ls

$ ./hello TTrojan

Finally, let’s go back to our home directory which is up 2 levels of directory hierarchy. This can be achieved by typing: $ cd ../..

Page 13: EE355 Name: Getting Started - USC Ming Hsieh Department of

EE 355 Linux Tutorial - Linux Tutorial

Last Revised: 1/22/2013 13

Notice that the first ‘..’ would put us into ‘ee355’ and that the second ‘..’ would go up one more level to our home directory. The ‘/’ is just a separator of directory names. However, there is a faster way to go to your home directory form WHEREVER you are by typing: $ cd ~ or just $ cd

‘~’ is a reference to the current user’s home directory. In addition, ‘cd’ without any other arguments defaults to the user’s home directory.

7 Review 1. How could you copy all the files from the current directory to its parent

directory 2. How could you move all the files that end with an extension *.h in your

home directory to the current directory without knowing the full path to the current directory [Hint: use a shortcut for the home directory.]

3. Write a command sequence to make a directory called ‘backup’ underneath the current directory, then copy all the files in the current directory to “backup”

4. Write a single command to delete the ‘backup’ subdirectory of the current directory and all of the files underneath ‘backup’. [Hint: Use an option to the ‘rm’ command to help. Type ‘man rm’ at the prompt to see more info on the ‘rm’ options. Note: ‘man command’ will give help and usage info on that particular command and even works for most C/C++ library functions such as sin, cos, strlen, etc.]

5. Write a Unix/Linux command to check if the string “main” appeared in a file ‘test.c’ (assuming ‘test.c’ was in the current working directory)

6. If a program becomes unresponsive, what Linux command could you use to kill it? [Metaquestion: What program could you use to find the ID of the unresponsive program?]

8 Lab Report Submit your answers to the review questions online via Blackboard.