SlideShare a Scribd company logo
1 of 45
CS2281: Programming in UNIX
http://www.comp.nus.edu.sg/~cs2281
Lecture 1: Introduction
2
UNIX systems (1/2)
Courtesy of Hugh Anderson
3
UNIX systems (2/2)
! ?
Courtesy of Hugh Anderson
4
MULTICS (1965) – parent of UNIX
 Have a look at http://www.multicians.org/
 Written in PL/1, and was portable. It had
 Hierarchical directories
 A CLI interface
 Utilities (mail, editors, etc.)
 The last Multics system shut down in
2000 (!)
Courtesy of Hugh Anderson
5
UNIX history
 Well – they needed a computer to run
Ken Thompson’s “Space Travel” game…
 The UNIX Time-Sharing System, 1974
http://citeseer.ist.psu.edu/10962.html
Please read sections: I. Introduction, II. Hardware
and Software Environment, VIII. Perspective, IX.
Statistics.
 The Evolution of the Unix Time-sharing System,
1984
http://citeseer.ist.psu.edu/ritchie84evolution.html
Please read sections: Introduction, Origins, The
advent of the PDP-11, The first PDP-11 system,
High-level languages, Conclusion.
Courtesy of Hugh Anderson
6
UNIX and C
 C was developed in order to re-implement
UNIX (most work down in 1972)
 The Development of the C language, 1993
http://citeseer.ist.psu.edu/ritchie93development.html
Please read sections: Introduction, History: The
Setting, Embryonic C, Neonatal C, Successors,
Critique.
 In summary, C was a high-level language (for the
1970’s), and small and efficient enough to implement
an OS, even on the small machines of the day.
Courtesy of Hugh Anderson
7
UNIX 35 years on…
 According to Netcraft (August 2005) 78% of
(72M) web servers are UNIX based.
 Peer review, open source, standards, design,
GNU, stability, Portability-to-the-max (PDAs,
MacOSX, servers…)
 Virtually all complex S/W products started in
UNIX
 TCP/IP, web browsers, theorem provers, databases,
spreadsheets, Java, IDEs/RAD tools, Alias Systems
Corporation (Alias|Wavefront), renderfarms, search engines…
Courtesy of Hugh Anderson
8
UNIX (1/2)
 You may wish to try the following
commands:
cat "food in cans"
[ Where is my brain?
(-
mkdir yellow_pages; cat > yellow_pages
ping elvis.org | awk '{print substr($1,1,5), $2,$2}'
 UNIX is a multi-user multi-tasking
operating system. It is relatively stable,
and as a result, it is the most common OS
for servers on the Internet.
Courtesy of Hugh Anderson
9
UNIX (2/2)
 It is written almost entirely in C, and the
sources for various versions are available
for copying and inspection, making it the
most portable OS.
 UNIX distributions:
http://www.mirrorservice.org/packages/unix/
 Mini distributions: http://www.cotse.com/miniunix.htm
Courtesy of Hugh Anderson
10
C (1/2)
 C has been described as:
“a language that combines all the elegance
and power of assembly language…
with all the readability and maintainability of
assembly language” (!)
Courtesy of Hugh Anderson
11
C (2/2)
 C is procedural, not OO
 OO means you concern yourself with the
components (objects) of your system
 Procedural means… what do I do next…
(instead of what do I do it to…)
 Library do anything, but are generally
much less safe than Java
Courtesy of Hugh Anderson
12
C: Horrible code
 Here is an example of correct, but
extremely hard to read code:
Courtesy of Hugh Anderson
13
C: Obfuscated code
 This code comes from an interesting website
devoted to the worst-of-the-worst-of-the-worst
C code.
 The International Obfuscated C Code Contest
at http://www.ioccc.org/.
 C programmers from around the world compete
to write the worst C code every year.
 You may find it interesting to find out how not to
write C.
Courtesy of Hugh Anderson
14
An Example C Program
Courtesy of Hugh Anderson
15
C: Comments
 The first six lines of the program are an
(optional) comment. Comments are
placed between /* and */ symbols, or
(Java like) after a //.
 You are put header comments something
like the above one in every program you
submit during this course.
 You might want to spend a little time with
an editor, and create a master header
that you can use in all your C programs.
Courtesy of Hugh Anderson
16
C: main()
 The main part of the program to be run is
always called main. This is just a tradition.
It could have been called ‘program’ or
‘starting-place’ or just about anything, but
the designers decided to use the word
‘main’.
 Not ‘Main’, ‘MAIN’, or ‘MaIn’.
 Case-sensitive in C.
Courtesy of Hugh Anderson
17
C: body
 The body of the program contains a
single statement which prints out the
message Hello Singapore! Followed by a
newline character n.
 The printf is called a statement or a
command.
Courtesy of Hugh Anderson
18
C: printf (1/3)
 The C statement printf can be used in a
few different ways, but this way is the
simplest.
 The string within the quotes is printed out
on the console.
 The “n” indicates that a new line is added
to the output – shifting suceeding outputs
onto the next line.
Courtesy of Hugh Anderson
19
C: printf (2/3)
 The format given here for printf is:
printf ( <string> );
 On a UNIX system, the online help can
give you detailed information about each
C programming construct.
Courtesy of Hugh Anderson
20
C: printf (3/3)
 If you use the UNIX command “man
printf”, or “man –s 3c printf”, you get:
Courtesy of Hugh Anderson
21
UNIX editors – terminal: pico
Courtesy of Hugh Anderson
22
UNIX editors – terminal: emacs
Courtesy of Hugh Anderson
23
UNIX editors – X: emacs
Courtesy of Hugh Anderson
24
UNIX editors – X: nedit
Courtesy of Hugh Anderson
25
Safety
 C can be ‘unsafe’
 In Java:
 In C:
Courtesy of Hugh Anderson
String str1, str2;
. . .
str1 = str2;
char str1[10], str2[10];
. . .
strcpy(str1, str2);
26
String copy (1/2)
 char str1[10] – allocates 10 characters for a
string
 strcpy – copies the second string to the first
 printf - %s specifies the format used to print the
argument
Courtesy of Hugh Anderson
int main() {
char str1[10], str2[10];
strcpy(str1, "Important");
printf("Contents of str1: %sn", str1);
}
27
String copy (2/2)
Courtesy of Hugh Anderson
int main() {
char str1[10], str2[10];
strcpy(str1, "Important");
strcpy(str2, "Not quite so important");
printf("Contents of str1: %sn", str1);
}
28
Warnings to the compiler
We get warnings – so fix these first.
Courtesy of Hugh Anderson
#include <stdio.h>
int main() {
char str1[10], str2[10];
strcpy(str1, "Important");
strcpy(str2, "Not quite so important");
printf("Contents of str1: %sn", str1);
return 0;
}
Compile: gcc -Wall
29
No compilation error, but…
Courtesy of Hugh Anderson
Output:
ortant
Aaaaaaarrgggghhhh!
The storage locations for str1 and str2 are…
30
Hello Singapore
Courtesy of Hugh Anderson
#include <stdio.h>
int main() {
printf("Hello Singapore!n");
return 0;
}
31
#include <stdio.h>
 Include a standard file.
 Any C line that begins with # is pre-
processed with a program called the C
pre-processor (cpp).
 #include is textual replacement.
Courtesy of Hugh Anderson
32
Compilation (1/2)
 gcc hello.c
 gcc –o hello hello.c
 gcc –g –o hello hello.c
 gcc –g –Wall –o hello hello.c
Courtesy of Hugh Anderson
33
Compilation (2/2)
gcc x.c is…
Courtesy of Hugh Anderson
cpp – C pre-processor
cc1 – compiler to assembly language
as – assembles to an object module
ld – links object modules to executable
C C .s .o
U U U U
cpp cc1 as ld
(C source) (C source) (Assembler) (Object
module)
(Executable)
34
C: Tokens
 The compiler splits the program into
tokens. For our first program, the tokens
would be:
Courtesy of Hugh Anderson
main ( ) { printf ( "Hello Singapore!n" ) ; }
35
Writing clear code
 We could write our program just like this:
main(){printf("Hello Singapore!n");}
and the program would compile and run
accurately.
 However, we do not do this. It is a
common programming practice to try as
much as possible to make our programs
readable.
Courtesy of Hugh Anderson
36
An aside into UNIX
 Look at with ps or ps –f or ps –fl or
ps –efl:
Courtesy of Hugh Anderson
Note parent process…
37
pstree
 pstree on Linux:
Courtesy of Hugh Anderson
38
UNIX process hierarchy
 The first process is init (process id 1).
 All other processes descend from it, so
we have a tree.
 We will see this later, but processes
create new processes using a fork()
system call.
Courtesy of Hugh Anderson
39
UNIX system calls (1/2)
 When a process runs some functions are
critical, and are only performed by the OS
kernel.
 In our “Hello Singapore” program, all
output (I/O) is considered critical, and so
the printf() call in the program will end up
performing a system call.
 Similarly for fork() – creating new
processes.
Courtesy of Hugh Anderson
40
UNIX system calls (2/2)
Courtesy of Hugh Anderson
41
Back to C compilation
Courtesy of Hugh Anderson
42
Typical Unix command
& run in backgrund (simultaneously)
; command separator
() bracketed expression
Courtesy of Hugh Anderson
gcc ic.c & (/usr/ucb/ps –a; /usr/ucb/ps –a; /usr/ucb/ps –a)
 The interpretation of these symbols is done
by the shell program, in this case bash.
43
C compilation
Courtesy of Hugh Anderson
44
C compilation by hand
Courtesy of Hugh Anderson
45
End of file

More Related Content

Similar to lect01.ppt

Introduction khgjkhygkjiyhgikjyhgikygkii
Introduction khgjkhygkjiyhgikjyhgikygkiiIntroduction khgjkhygkjiyhgikjyhgikygkii
Introduction khgjkhygkjiyhgikjyhgikygkii
cmdept1
 
Linuxppt
LinuxpptLinuxppt
Linuxppt
Reka
 

Similar to lect01.ppt (20)

Shell & Shell Script
Shell & Shell ScriptShell & Shell Script
Shell & Shell Script
 
Shell & Shell Script
Shell & Shell Script Shell & Shell Script
Shell & Shell Script
 
Linuxppt
LinuxpptLinuxppt
Linuxppt
 
Unix - An Introduction
Unix - An IntroductionUnix - An Introduction
Unix - An Introduction
 
Terminal basic-commands(Unix) -partI
Terminal basic-commands(Unix) -partITerminal basic-commands(Unix) -partI
Terminal basic-commands(Unix) -partI
 
Introduction-to-Linux.pptx
Introduction-to-Linux.pptxIntroduction-to-Linux.pptx
Introduction-to-Linux.pptx
 
Introduction to-linux
Introduction to-linuxIntroduction to-linux
Introduction to-linux
 
Introduction-to-Linux.pptx
Introduction-to-Linux.pptxIntroduction-to-Linux.pptx
Introduction-to-Linux.pptx
 
Introduction khgjkhygkjiyhgikjyhgikygkii
Introduction khgjkhygkjiyhgikjyhgikygkiiIntroduction khgjkhygkjiyhgikjyhgikygkii
Introduction khgjkhygkjiyhgikjyhgikygkii
 
Unix Operating System
Unix Operating SystemUnix Operating System
Unix Operating System
 
Whole c++ lectures ITM1 Th
Whole c++ lectures ITM1 ThWhole c++ lectures ITM1 Th
Whole c++ lectures ITM1 Th
 
Summarized of UNIX Time Sharing System
Summarized of UNIX Time Sharing SystemSummarized of UNIX Time Sharing System
Summarized of UNIX Time Sharing System
 
How To Add System Call In Ubuntu OS
How To Add System Call In Ubuntu OSHow To Add System Call In Ubuntu OS
How To Add System Call In Ubuntu OS
 
Unix final
Unix finalUnix final
Unix final
 
Introduction of c language
Introduction of c languageIntroduction of c language
Introduction of c language
 
Unix
UnixUnix
Unix
 
Linuxppt
LinuxpptLinuxppt
Linuxppt
 
Shell Scripting and Programming.pptx
Shell Scripting and Programming.pptxShell Scripting and Programming.pptx
Shell Scripting and Programming.pptx
 
Shell Scripting and Programming.pptx
Shell Scripting and Programming.pptxShell Scripting and Programming.pptx
Shell Scripting and Programming.pptx
 
Linuxppt
LinuxpptLinuxppt
Linuxppt
 

More from DrSamsonChepuri1 (8)

CYBER SECURITY :Cyber Law – The Legal Perspectives
CYBER SECURITY :Cyber Law – The Legal PerspectivesCYBER SECURITY :Cyber Law – The Legal Perspectives
CYBER SECURITY :Cyber Law – The Legal Perspectives
 
remoteing.ppt
remoteing.pptremoteing.ppt
remoteing.ppt
 
e-comm new2.ppt
e-comm new2.ppte-comm new2.ppt
e-comm new2.ppt
 
BASIC LAWS OF CONSUPTION AND DEMAND ANALYSIS.ppt
BASIC LAWS OF CONSUPTION AND DEMAND ANALYSIS.pptBASIC LAWS OF CONSUPTION AND DEMAND ANALYSIS.ppt
BASIC LAWS OF CONSUPTION AND DEMAND ANALYSIS.ppt
 
loops in C ppt.pdf
loops in C ppt.pdfloops in C ppt.pdf
loops in C ppt.pdf
 
how-to-write-an-abstract_medical.ppt
how-to-write-an-abstract_medical.ppthow-to-write-an-abstract_medical.ppt
how-to-write-an-abstract_medical.ppt
 
research_paper_powerpoint.ppt
research_paper_powerpoint.pptresearch_paper_powerpoint.ppt
research_paper_powerpoint.ppt
 
ASN_ ppt.ppt
ASN_ ppt.pptASN_ ppt.ppt
ASN_ ppt.ppt
 

Recently uploaded

VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
Epec Engineered Technologies
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 

lect01.ppt

  • 1. CS2281: Programming in UNIX http://www.comp.nus.edu.sg/~cs2281 Lecture 1: Introduction
  • 2. 2 UNIX systems (1/2) Courtesy of Hugh Anderson
  • 3. 3 UNIX systems (2/2) ! ? Courtesy of Hugh Anderson
  • 4. 4 MULTICS (1965) – parent of UNIX  Have a look at http://www.multicians.org/  Written in PL/1, and was portable. It had  Hierarchical directories  A CLI interface  Utilities (mail, editors, etc.)  The last Multics system shut down in 2000 (!) Courtesy of Hugh Anderson
  • 5. 5 UNIX history  Well – they needed a computer to run Ken Thompson’s “Space Travel” game…  The UNIX Time-Sharing System, 1974 http://citeseer.ist.psu.edu/10962.html Please read sections: I. Introduction, II. Hardware and Software Environment, VIII. Perspective, IX. Statistics.  The Evolution of the Unix Time-sharing System, 1984 http://citeseer.ist.psu.edu/ritchie84evolution.html Please read sections: Introduction, Origins, The advent of the PDP-11, The first PDP-11 system, High-level languages, Conclusion. Courtesy of Hugh Anderson
  • 6. 6 UNIX and C  C was developed in order to re-implement UNIX (most work down in 1972)  The Development of the C language, 1993 http://citeseer.ist.psu.edu/ritchie93development.html Please read sections: Introduction, History: The Setting, Embryonic C, Neonatal C, Successors, Critique.  In summary, C was a high-level language (for the 1970’s), and small and efficient enough to implement an OS, even on the small machines of the day. Courtesy of Hugh Anderson
  • 7. 7 UNIX 35 years on…  According to Netcraft (August 2005) 78% of (72M) web servers are UNIX based.  Peer review, open source, standards, design, GNU, stability, Portability-to-the-max (PDAs, MacOSX, servers…)  Virtually all complex S/W products started in UNIX  TCP/IP, web browsers, theorem provers, databases, spreadsheets, Java, IDEs/RAD tools, Alias Systems Corporation (Alias|Wavefront), renderfarms, search engines… Courtesy of Hugh Anderson
  • 8. 8 UNIX (1/2)  You may wish to try the following commands: cat "food in cans" [ Where is my brain? (- mkdir yellow_pages; cat > yellow_pages ping elvis.org | awk '{print substr($1,1,5), $2,$2}'  UNIX is a multi-user multi-tasking operating system. It is relatively stable, and as a result, it is the most common OS for servers on the Internet. Courtesy of Hugh Anderson
  • 9. 9 UNIX (2/2)  It is written almost entirely in C, and the sources for various versions are available for copying and inspection, making it the most portable OS.  UNIX distributions: http://www.mirrorservice.org/packages/unix/  Mini distributions: http://www.cotse.com/miniunix.htm Courtesy of Hugh Anderson
  • 10. 10 C (1/2)  C has been described as: “a language that combines all the elegance and power of assembly language… with all the readability and maintainability of assembly language” (!) Courtesy of Hugh Anderson
  • 11. 11 C (2/2)  C is procedural, not OO  OO means you concern yourself with the components (objects) of your system  Procedural means… what do I do next… (instead of what do I do it to…)  Library do anything, but are generally much less safe than Java Courtesy of Hugh Anderson
  • 12. 12 C: Horrible code  Here is an example of correct, but extremely hard to read code: Courtesy of Hugh Anderson
  • 13. 13 C: Obfuscated code  This code comes from an interesting website devoted to the worst-of-the-worst-of-the-worst C code.  The International Obfuscated C Code Contest at http://www.ioccc.org/.  C programmers from around the world compete to write the worst C code every year.  You may find it interesting to find out how not to write C. Courtesy of Hugh Anderson
  • 14. 14 An Example C Program Courtesy of Hugh Anderson
  • 15. 15 C: Comments  The first six lines of the program are an (optional) comment. Comments are placed between /* and */ symbols, or (Java like) after a //.  You are put header comments something like the above one in every program you submit during this course.  You might want to spend a little time with an editor, and create a master header that you can use in all your C programs. Courtesy of Hugh Anderson
  • 16. 16 C: main()  The main part of the program to be run is always called main. This is just a tradition. It could have been called ‘program’ or ‘starting-place’ or just about anything, but the designers decided to use the word ‘main’.  Not ‘Main’, ‘MAIN’, or ‘MaIn’.  Case-sensitive in C. Courtesy of Hugh Anderson
  • 17. 17 C: body  The body of the program contains a single statement which prints out the message Hello Singapore! Followed by a newline character n.  The printf is called a statement or a command. Courtesy of Hugh Anderson
  • 18. 18 C: printf (1/3)  The C statement printf can be used in a few different ways, but this way is the simplest.  The string within the quotes is printed out on the console.  The “n” indicates that a new line is added to the output – shifting suceeding outputs onto the next line. Courtesy of Hugh Anderson
  • 19. 19 C: printf (2/3)  The format given here for printf is: printf ( <string> );  On a UNIX system, the online help can give you detailed information about each C programming construct. Courtesy of Hugh Anderson
  • 20. 20 C: printf (3/3)  If you use the UNIX command “man printf”, or “man –s 3c printf”, you get: Courtesy of Hugh Anderson
  • 21. 21 UNIX editors – terminal: pico Courtesy of Hugh Anderson
  • 22. 22 UNIX editors – terminal: emacs Courtesy of Hugh Anderson
  • 23. 23 UNIX editors – X: emacs Courtesy of Hugh Anderson
  • 24. 24 UNIX editors – X: nedit Courtesy of Hugh Anderson
  • 25. 25 Safety  C can be ‘unsafe’  In Java:  In C: Courtesy of Hugh Anderson String str1, str2; . . . str1 = str2; char str1[10], str2[10]; . . . strcpy(str1, str2);
  • 26. 26 String copy (1/2)  char str1[10] – allocates 10 characters for a string  strcpy – copies the second string to the first  printf - %s specifies the format used to print the argument Courtesy of Hugh Anderson int main() { char str1[10], str2[10]; strcpy(str1, "Important"); printf("Contents of str1: %sn", str1); }
  • 27. 27 String copy (2/2) Courtesy of Hugh Anderson int main() { char str1[10], str2[10]; strcpy(str1, "Important"); strcpy(str2, "Not quite so important"); printf("Contents of str1: %sn", str1); }
  • 28. 28 Warnings to the compiler We get warnings – so fix these first. Courtesy of Hugh Anderson #include <stdio.h> int main() { char str1[10], str2[10]; strcpy(str1, "Important"); strcpy(str2, "Not quite so important"); printf("Contents of str1: %sn", str1); return 0; } Compile: gcc -Wall
  • 29. 29 No compilation error, but… Courtesy of Hugh Anderson Output: ortant Aaaaaaarrgggghhhh! The storage locations for str1 and str2 are…
  • 30. 30 Hello Singapore Courtesy of Hugh Anderson #include <stdio.h> int main() { printf("Hello Singapore!n"); return 0; }
  • 31. 31 #include <stdio.h>  Include a standard file.  Any C line that begins with # is pre- processed with a program called the C pre-processor (cpp).  #include is textual replacement. Courtesy of Hugh Anderson
  • 32. 32 Compilation (1/2)  gcc hello.c  gcc –o hello hello.c  gcc –g –o hello hello.c  gcc –g –Wall –o hello hello.c Courtesy of Hugh Anderson
  • 33. 33 Compilation (2/2) gcc x.c is… Courtesy of Hugh Anderson cpp – C pre-processor cc1 – compiler to assembly language as – assembles to an object module ld – links object modules to executable C C .s .o U U U U cpp cc1 as ld (C source) (C source) (Assembler) (Object module) (Executable)
  • 34. 34 C: Tokens  The compiler splits the program into tokens. For our first program, the tokens would be: Courtesy of Hugh Anderson main ( ) { printf ( "Hello Singapore!n" ) ; }
  • 35. 35 Writing clear code  We could write our program just like this: main(){printf("Hello Singapore!n");} and the program would compile and run accurately.  However, we do not do this. It is a common programming practice to try as much as possible to make our programs readable. Courtesy of Hugh Anderson
  • 36. 36 An aside into UNIX  Look at with ps or ps –f or ps –fl or ps –efl: Courtesy of Hugh Anderson Note parent process…
  • 37. 37 pstree  pstree on Linux: Courtesy of Hugh Anderson
  • 38. 38 UNIX process hierarchy  The first process is init (process id 1).  All other processes descend from it, so we have a tree.  We will see this later, but processes create new processes using a fork() system call. Courtesy of Hugh Anderson
  • 39. 39 UNIX system calls (1/2)  When a process runs some functions are critical, and are only performed by the OS kernel.  In our “Hello Singapore” program, all output (I/O) is considered critical, and so the printf() call in the program will end up performing a system call.  Similarly for fork() – creating new processes. Courtesy of Hugh Anderson
  • 40. 40 UNIX system calls (2/2) Courtesy of Hugh Anderson
  • 41. 41 Back to C compilation Courtesy of Hugh Anderson
  • 42. 42 Typical Unix command & run in backgrund (simultaneously) ; command separator () bracketed expression Courtesy of Hugh Anderson gcc ic.c & (/usr/ucb/ps –a; /usr/ucb/ps –a; /usr/ucb/ps –a)  The interpretation of these symbols is done by the shell program, in this case bash.
  • 44. 44 C compilation by hand Courtesy of Hugh Anderson

Editor's Notes

  1. Welcome
  2. Welcome
  3. Welcome