0. Reminder
Bring along your NUSNET account password slip to this lab! It is the one with the account number beginning with U08 (for freshmen).
1. Introduction
This laboratory is designed to give you an introduction to the sunfire machine as well as the basic C programming environment available on this machine. This practical session will also help you to become familiar with the process of editing, compiling, and running simple C programs.
1.1 Objectives
The objectives of this initial laboratory session is to show students how to use the SoC machines (particularly sunfire) and the C compiler for their assignments:
- login to the sunfire machine
- create and modify programs using the sunfire machine
- compile and execute C programs
- submit your files
- manipulate files
If you are unable to finish this lab before the end of your lab session, do not worry! Finish it up at your own time. You just need to ensure that you submit the three required files by Monday 01 September 2008, 23:59 hours.
2. Logging In
You should be greeted with a Windows screen. (If the PC is not on, switch it on.) As instructed on the screen, press Ctrl-Alt-Delete.
A login screen appears. You are to type in your NUSNET user-id, your NUSNET password, and select the NUSSTU domain. For students registered this year, your NUSNET user-id begins with u08 followed by 5 digits (example: u0801234, note that it is a small letter u), this is different from your matric number which has less digits and a check character at the back (example: U081234A, note that it is a capital letter U).
Note: All NUS students are issued with the NUSNET account by the Computer Centre. The domain name of this account is "@nus.edu.sg". All SoC students, as well as students from other faculties taking SoC modules, are also issued with SoC UNIX account. The domain name of the SoC account is "@comp.nus.edu.sg". This SoC UNIX account will be purged at the end of the semester for non-SoC students. Do not mix up these two accounts.
Start up a web browser (either Internet Explorer or Firefox), and click HERE to create your Unix Account (use a maximum of 8 characters in your password or you may encounter problems). You must do this before you are able to login to your Unix account. You need to do this only once for the whole semester.
After you have cleared this, you have to log into the SoC server using SSH Secure Shell Client. You can download SSHSecureShellClient-3.2.9.exe from the Windows Software folder in the IVLE Workbin.
Left mouse click on the Start button at the bottom-left corner, select All Programs, look for SSH Secure Shell folder, and left click on Secure Shell Client. A screen similar to the one shown below will appear. Click on Quick Connect button and a small window Connect to Remote Host will pop out.
Under Host Name, enter either sunfire-r.comp.nus.edu.sg (works from within NUS or from any of the local ISPs, e.g. SingNet, StarHub, PacNet) or sunfire.comp.nus.edu.sg (works from within NUS only). You should use sunfire-r.comp.nus.edu.sg unless it does not work. Please ensure that you have already created your Unix Account as shown above. Your Unix Account is not the same as your NUSNET Account. If connecting to sunfire-r.comp.nus.edu.sg still does not work, you need to install and connect to NUS first using NUS VPN.
Under User Name, enter your SoC user-id. Unix is case sensitive, so you must type "u08" and not "U08".
Ensure that the Port Number is 22 and click on the Connect button.
![]()
If you encounter the following window, just click "Yes".
![]()
When this is done, another small window will appear to prompt you for your password. Note that the user-id and password are case-sensitive (i.e. an "a" is different from an "A").
The password will appear on the screen as asterisks (***) so you need to type slowly and carefully.
Once you have logged into sunfire, you are automatically placed in your home directory. A directory is similar to a folder in Windows.
2.1 Notes before you proceed
- Do not click on the Close button (the button with a cross) at the top-right corner of the window. The correct way to log out of your UNIX account is explained in Section 9.
- The UNIX system is not GUI-based so the mouse is seldom used (if at all).
- You should see the UNIX prompt (read Section 5). If you don't, check that you have not scrolled off the screen with the mouse. Bring the prompt back into view by scrolling back.
- If you do see the UNIX prompt but whatever you type does not appear, you might have accidentally locked your screen (locking can be done by pressing control-S or by pressing the "Scroll Lock" key). Unlock your screen by pressing control-Q (if you have pressed control-S earlier), or by pressing "Scroll Lock" again (if you have pressed "Scroll Lock" earlier).
- If you get stuck after typing a command or in a middle of an application, sometimes typing 'q' (quit) may get you out.
- If 'q' does not work, press control-C which is the interrupt key. Use this as the last resort. If it still doesn't work, seek help.
- Do not press control-Z, which is the interrupt key in DOS. Pressing control-Z in UNIX sends your job to the background, and if you have accidentally pressed control-Z, type 'fg' (foreground) to resume.
- Tip 1: You may use the up and down arrows to select a previously entered command. This saves you some typing time.
- Tip 2: You may use the tab key to fill out the complete filename. Ask your lab TA to show you how this can be done.
2.2 User-Ids and Passwords
When you have logged in successfully, you will be immediately asked if you would like to change your password. Enter 'n' (no) to skip it. Do NOT change your password as you are still new to the system and if you make any mistake, time may be wasted as you need to get it rectified at the Help Desk (located on ground floor of S15).
You may want to change your password some other time, after you have thought of a good password. Choose a password that is 6 to 8 characters long.
There are guidelines to choosing good passwords which are safer and less susceptible to break-ins. When you change your password, the system will check that your new password satisfies its stringent requirements, failing which it will reject the change. Generally, the system tends to accept passwords that consist of at least a mix of uppercase and lowercase characters, plus some digits. It is advisable that you prepare a few passwords before-hand, so that if one fails to pass the test, you can pick another without wasting too much time. (Refer to this web page to find out more after this lab.) You can change your password any time you like -- in fact, you are advised to change it regularly. The command to change password is "passwd". It will take half an hour to one hour before your new password takes effect.
Always remember your password! If you forget, you would need to approach the personnel at the Help Desk (ground floor, S15) to submit a request for a new password. Alternatively, you can click HERE to change your password online (this requires your NUSNET ID and password).
3. Setting up your Account
IMPORTANT: This step must be correctly done or else you will NOT be able to submit your programs!
Run the setup program as follows (you should do this only ONCE). Type the following commands in your SSH Secure Shell window:
~cs1101c/lab0/setupCheck that you enter the above command ACCURATELY (the tilde character ~ is usually found on the top left of your keyboard next to the "1" key). This command initialises your account and prepares it for this initial lab session. It creates the "c" and "doc" directories (a directory is like a folder), and copies some files into your account (so that you don't have to type them from scratch). Refer to Appendix A for a list of these files and their descriptions.
After the setup program runs successfully, you must type:
source .bash_profileThis sets up useful commands for your program submission later. Remember to type the SPACE in between "source" and ".bash_profile". "Respect the spaces". Note that if the above command ran successfully, you will see no output. With many Unix commands, "no news is good news". This is very different from Windows or Mac where you are used to seeing a dialog box pop out. Try to get used to Unix quickly.
4. Online Help
An online help facility is available in the system via the "man" command ("man" stands for MANual). Type "man man" and refer to this web page to find out more about the facility. To look for more information about any UNIX command, for example, "ls", type "man ls". To exit "man", press "q".
5. Basic UNIX Commands
The following are a few commonly used commands. This list is by no means exhaustive and you are urged to explore on your own. Note that UNIX commands are case-sensitive.
In the examples below, bold words are commands which you are expected to enter. Assume that you are u0801234, your default prompt may look like this (possibly a little different):
u0801234@sf3:~[xxx]$sf3 is the internal name for sunfire; ~ indicates that you are currently in your home directory.
a. Directory commands
pwd to Print current Working Directory to show you which directory you are currently in u0801234@sf3:~[xxx]$ pwd /home/nusstu/u0801234ls to LiSt files in your current directory u0801234@sf3:~[xxx]$ ls c docYou may also use "ls -F" for more information (-F is one of the many options/flags available for the ls command. To see a complete list of the options, refer to the man pages, ie. "man ls".) u0801234@sf3:~[xxx]$ ls -F c/ doc/The slash (/) beside the filename tells you that the file is a directory (folder). A normal file does not have a slash (/) beside its name when "ls -F" is used. You may also use the "ls -l" command (dash L) to display almost all the file information, include the size of the file and the date of modification. Try it now! cd to Change Directory from current directory to another u0801234@sf3:~[xxx]$ cd c u0801234@sf3:~/c[xxx]$ ls -F ch1_1.c ch2_1.c ch2_2.c ch2_3.c ch2_4.cNote that the prompt changes to ~/c to indicate that you are now in the c directory below your HOME directory.
Entering "cd" alone brings you back to your HOME directory, ie. the directory in which you started with when you first logged into the system. u0801234@sf3:~/c[xxx]$ cd u0801234@sf3:~[xxx]$mkdir to MaKe a subDIRectory in current directory u0801234@sf3:~[xxx]$ mkdir another u0801234@sf3:~[xxx]$ ls -F another/ c/ doc/rmdir to ReMove a subDIRectory in current directory -- note that a directory must be empty before it can be removed. u0801234@sf3:~[xxx]$ rmdir another u0801234@sf3:~[xxx]$ ls -F c/ doc/b. File commands
cp to CoPy files u0801234@sf3:~[xxx]$ cd doc u0801234@sf3:~/doc[xxx]$ cp abridged.txt anotherfile u0801234@sf3:~/doc[xxx]$ ls abridged.txt anotherfile faq.txt tutormv to MoVe files from one directory to another; can also be used to rename files. u0801234@sf3:~/doc[xxx]$ mv anotherfile afile u0801234@sf3:~/doc[xxx]$ ls abridged.txt afile faq.txt tutorrm to ReMove files. Be careful with this command -- files deleted cannot be restored (unless they have been backed up during the normal backup cycle). u0801234@sf3:~/doc[xxx]$ rm afile rm: remove `afile'? y u0801234@sf3:~/doc[xxx]$ ls abridged.txt faq.txt tutorc. Command to display text files
cat to string together or display (CATenate) the contents of files onto the screen u0801234@sf3:~/doc[xxx]$ cat abridged.txtless variant of "cat" (includes features to read each page leisurely) u0801234@sf3:~/doc[xxx]$ less -e abridged.txtIn "less", use <space> to move down one page, 'b' to move Back up one page, and 'q' to Quit from "less".
6. Running a C Program
The process of creating a working C program involves the following steps:
+---------+ +---+-->| EDIT | | ^ +---------+ | | | | | | | | v | | +---------+ | +---| COMPILE | | +---------+ | | | | | v | +---------+ +-------| RUN | +---------+
- Use an editor of your choice, type in the source code (filename must have extension .c, eg: ch1_1.c)
- Compile your program to obtain the executable file (with default name a.out). If there are compilation errors, identify them and re-edit the source code before you proceed.
- Run your executable file by typing the name of the executable file.
If there are run-time errors, you must identify them and re-edit the source code, and compile again.6.1 A sample C program
Three sample C programs have been copied into your "c" subdirectory. Use "cat" or "less" to view the program "ch1_1.c".
u0801234@sf3:~/doc[xxx]$ cd u0801234@sf3:~[xxx]$ cd c u0801234@sf3:~/c[xxx]$ less -e ch1_1.c
/*---------------------------------------------------*/ /* Program chapter1_1 */ /* */ /* This program computes the */ /* distance between two points. */ #include <stdio.h> #include <math.h> int main(void) { /* Declare and initialize variables. */ double x1=1, y1=5, x2=4, y2=7, side_1, side_2, distance; /* Compute sides of a right triangle. */ side_1 = x2 - x1; side_2 = y2 - y1; distance = sqrt(side_1*side_1 + side_2*side_2); /* Print distance. */ printf("The distance between the two points is " "%5.2f \n",distance); /* Exit program. */ return 0; } /*---------------------------------------------------*/Compile and run the program as follows (use the "gcc" compiler):
u0801234@sf3:~/c[xxx]$ gcc -Wall -lm ch1_1.c(this will compile "ch1_1.c" and produce the executable file "a.out". Note that we must use the "-lm" flag (dash L M) whenever our C program contains the line #include <math.h>. The "-Wall" flag tells the compiler to generate all warnings. Note that the W in "-Wall" must be an uppercase letter. C is case-sensitive.
Note that if gcc compiles your program successfully, you will see no output. With gcc, "no news is good news". You are now ready to execute your program by typing the next command:
u0801234@sf3:~/c[xxx]$ ./a.outThis will execute the file "a.out". Note that we prefix it with "./" to indicate that "a.out" is in the current directory.
7. Creating your own C Programs
7.1 Create your first C program "first.c"
There are a number of editors available in sunfire: Vim, vi, emacs, joe, pico, etc. The more powerful one requires a longer time to learn. For this lab, you will use Vim -- a powerful editor with many commands, but even with the knowledge of a few simple commands it is quite easy to use and very powerful. It is YOUR responsibility to pick an editor and master it, and in future labs we will assume that you are familiar with your editor and its various functions.
Get into your c subdirectory if you are not there. Enter "vim first.c", then press the "i" key. You will see that the words "-- INSERT --" appear on the bottom left corner of your screen. You are now in INSERT mode. While you are in INSERT mode, you may use the arrow keys (Up, Down, Left, Right) to move around your program, as well as the Backspace key and Delete key to delete text. The PageUp and PageDown keys do not work, so do not use them. Do not use the scroll bar as it does not always work as expected.
Notice that line numbers (1, 2, 3, etc.) are displayed on the left. This helps you to easily identify a number by its line. Line numbers are NOT part of C code. This is extremely useful when identifying the location of compilation errors.
To copy text, you may use the mouse to highlight blocks of text, then right-click on the mouse and choose Copy. To paste your text, you must use the cursor keys to move the cursor to the desired position, then right-click on the mouse and choose Paste.
Type in the following program:
#include <stdio.h> int main(void) { int a=27, b=6, c; c = a%b; printf("The value of c is %i.\n", c); return 0; }Note that for simplicity, the above program has no documentation. A good program should include documentation, at least the identity of the author, the purpose of the program and other relevant information. Keep this in mind when you write your own programs.
When you are done, press "<ESC>:x<ENTER>" (more clearly seen as pressing the following four keys one after another: <ESC> : x <ENTER>) to save your program and exit from the Vim editor. <ESC> means press the Escape key, then press the colon key (shift-;), then press x (the x is a lowercase x), and finally <ENTER> means press the Enter key.
If you want to save your file without exiting from the Vim editor, press "<ESC>:w<ENTER>", then press the "i" key again to go back into INSERT mode. It is a good habit to save your file periodically so that if the network or the system goes down for any reason, you will not lose your hard work.
When you startup Vim, it begins in COMMAND mode. One way to go into INSERT mode is to press the "i" key. While we are in INSERT mode, we can type in our C code. To switch back to COMMAND mode, we press the "<ESC>" key.
The following shows you a list of useful commands in Vim:
- <ESC>:x<ENTER> : Saves your program and exits from Vim.
- <ESC>:wq<ENTER> : Saves your program and exits from Vim.
- <ESC>ZZ : (Note that the Zs are uppercase) Saves your program and exits from Vim.
- <ESC>:q!<ENTER> : Exits from Vim without saving your program.
- <ESC>ZQ : Exits from Vim without saving your program.
If you would like to learn more about Vim commands (do this after the lab), click HERE. Another useful reference can be found HERE.
7.2 Compile and run your program
u0801234@sf3:~/c[xxx]$ gcc -Wall first.cThere will be error messages if your program has errors. Go to Step 7.1 to make the necessary corrections and re-compile. If there are no compilation errors, proceed with program execution as follows:
u0801234@sf3:~/c[xxx]$ ./a.outNote that this "a.out" file is the executable version of "first.c", and it has replaced the earlier "a.out" file which is the executable file of "ch1_1.c", since there must not be two files with the same name in a directory. To avoid this, you may specify the name of the executable file, instead of leaving it to the system to use the default name "a.out". The trick lies in the "-o" option of the "gcc" command:
u0801234@sf3:~/c[xxx]$ gcc -Wall first.c -o firstIn the above example, the executable file for "first.c" will be called "first" instead of "a.out". Note that the name of the executable file MUST IMMEDIATELY follow the -o. Be careful of this or you may lose your source file!
Do NOT ever type the following:
u0801234@sf3:~/c[xxx]$ gcc -Wall first.c -o first.cWhat is wrong with the above statement? It states that you want to output the executable file to first.c. This is wrong, because the executable file should be called first. If you type the command wrongly, you will LOSE YOUR SOURCE FILE, and you would have to start typing your source file all over again, wasting your time and your effort. So be careful in what you type.
In UNIX, there is no need for the name of an executable file to have an extension. If you wish to find out more about the "gcc" command, read the man pages.
7.3 Another program
Use the instructions in Steps 7.1 and 7.2 to create, compile and run the following program "second.c". What is the output of the program? How could you add a blank line before and after the line of output, to make it into a 3-line output?
#include <stdio.h> int main(void) { float a; float b=6, c=18.6; a = b/c; printf("b is %3.1f, c is %3.1f. ", b, c); printf("a is %.6f.\n", a); return 0; }Experiment a little by changing the "3.1" and ".6" to some other values and try to figure out what they do (refer to Lecture 3). Try also to combine the two printf statements into one. Programming is fun in that you can try out all sorts of things and see the end results yourself! A lot can be learned through self-exploration alone!
7.4 A program with errors
The program "third.c" below contains syntax errors which will be reported during compilation. Though you may be new to C, the error messages do give some information, and by referring to the few correct sample programs above, you should be able to spot some, if not all, of the errors.
*/ This program contains MANY syntax errors /* include (stdio.h); int main(void) { float num num := 305.68; printf("num is ") printf('%6.1f\n', Num); return 0; }Edit the program edit to correct the errors. Compile it. If there are still errors, what must you do? Yes, edit the program again, and re-compile. Assuming that all errors have been corrected, what is the output of this program?
8. Submitting Your Programs
You are now ready to submit all your hard work! The submission program allows you to submit up to five C programs at one time. Submissions will overwrite files with the same filename. You may also submit as many times as you like as long as your submission is before the deadline. It is a good habit to frequently submit your work. Do not wait until the last minute to submit! If you miss the deadline even by one second, we're sorry but we cannot accept your submission because we must be fair to everyone who submitted on time.
To submit only the file "first.c", type:
u0801234@sf3:~/c[xxx]$ submit first.cTo check that your file has been successfully submitted, type:
u0801234@sf3:~/c[xxx]$ checkIt is essential that you always run the "check" command after you submit your files to ensure that you have submitted the correct files!
If you want to submit all three files together, type:
u0801234@sf3:~/c[xxx]$ submit first.c second.c third.cTry it now! Note that this second submission of "first.c" overwrites your previous submission of "first.c". Run the "check" command to confirm that you have successfully submitted all three files. Successful submission of all three files correctly with the correct filename (filenames are case-sensitive!) will get you five marks for succesfully completing this lab! Submitting only one file correctly will get you one mark; submitting only two files correctly will get you three marks.
The deadline for submission is Monday 01 September 2008, 23:59 hours.
9. Logging Out
When you have finished, you must always log out of the computer system as follows:
u0801234@sf3:~/c[xxx]$ logoutTyping "exit" or pressing ctrl-d will also have the same effect. You MUST remember to log out, otherwise anyone who comes by may delete all your valuable files away!
Similarly, if you find that someone has forgotten to logoff, just graciously log out for him or her. Don't even think of malice.
This logs you out of sunfire but you are in still in your NUSNET session. To log off from NUSNET, left mouse click the Start button at the bottom-left of the screen, click Shut-down and select Log Off xxxxxxxx (where xxxxxxxx is your NUSNET user-id).
You need not shut down the machine or switch off the PC.
10. After-Lab Assignments
You should carry on experimenting with more exercises. After today's lab, go over what you have done again by yourself, and you may do the following at your leisure.
- Compile and execute all the programs we have copied into your "c" directory. Understand how each of them work.
- Browse through the files we have copied into your "doc" directory. You may not understand its contents but you should know what it contains.
- Familiarise yourself with the UNIX environment as well as the Vim editor.
- To learn more about Vim, run the Vim tutor. Change to your "doc" directory and type "vim tutor". If you are interested to learn more Vim commands, click HERE. Another useful reference can be found HERE.
- Read the course website. Be familiar with IVLE especially the discussion forum and the workbin.
- Try out all the programs in the lectures that we have covered so far.
- Try out all the questions in the tutorials. Remember, the questions that we do not cover during the tutorials are compulsory for you to attempt on your own!
Appendix A
These are the files copied into your directories by the setup program.
In your home directory:
- .bash_profile: Personal initialisation file for login shells
- .bashrc: Personal per-interactive-shell startup file (for bash)
- .vimrc: Vim configuration file
Notes: Filenames that begin with a dot (.) are 'hidden files' and are not shown with the "ls" command. Use "ls -a" to see them.
In your "c" subdirectory:
- ch1_1.c: Computes the distance between two points.
- ch2_1.c: Prints two values as characters and integers.
- ch2_2.c: Uses linear interpolation to compute the freezing temperature of seawater.
- ch2_3.c: Estimates new velocity and acceleration values for a specified time.
- ch2_4.c: Prints the system limitations.
In your "doc" subdirectory:
- abridged.txt: Answers (abridged) to the C FAQ (Frequently Asked Questions).
- faq.txt: Answers (complete) to the C FAQ.
- tutor: The Vim tutor.
original document: Jan 13, 2004 by Aaron Tan
last amended: Aug 30, 2008 at 12:54 hours by Raymond Tan
This document, index.html, has been accessed 17 times since 25-Jun-24 11:57:13 +08. This is the 1st time it has been accessed today.A total of 14 different hosts have accessed this document in the last 393 days; your host, 216.73.216.189, has accessed it 1 times.
If you're interested, complete statistics for this document are also available, including breakdowns by top-level domain, host name, and date.