SlideShare ist ein Scribd-Unternehmen logo
1 von 33
Ubuntu and C
Contents
•Steps to write C programs on Terminal
•C Basic programs
Steps to write C programs on Terminal
• Open terminal : Press Ctrl+Alt+T: Ubuntu/Linux terminal
shortcut
• On shell prompt type as below:
$gedit filename.c
•This will start the gedit text editor.
• In editor type your program, save it and close editor.
Steps to write C programs on Terminal
• On shell prompt type:
gcc –o filename filename.c
• gcc, normally does preprocessing, compilation, assembly and
linking.
• This will create object file.
gcc -o writes the build output to an output file.
• Now type : ./filename for execution
Program 1: To find average of two numbers
#include <stdio.h>
int main()
{
int number1, number2;
float res;
printf("Enter the First Number to find = ");
scanf("%d",&number1);
printf("Enter the Second Number to find = ");
scanf("%d",&number2);
int sm = number1 + number2;
res = sm/2; //(float)sum/2;
printf("The Sum of %d and %d = %dn", number1, number2, sm);
printf("The Average of %d and %d = %.2fn", number1, number2, res);
return 0;
}
Program 1: To find average of two numbers
Steps to run C program on Ubuntu
student@AUHDT0766:~$ gedit add1.c
student@AUHDT0766:~$ gcc -o add1 add1.c
student@AUHDT0766:~$ ./add1
Enter the First Number to find = 23
Enter the Second Number to find = 45
The Sum of 23 and 45 = 68
The Average of 23 and 45 = 34.00
student@AUHDT0766:~$
Program 2: To find Volume of a Cube
#include<stdio.h>
void main()
{//start the program
int h,w,d,vol;//variables declaration
h=10;w=12;d=8;//assign value to variables
vol=h*w*d;//calculation usingmathematical formula
printf("The Volume of the cube is: %d",vol);//display the volume
return ;
//end the main program
}
Program 2: : To find Volume of a Cube
student@AUHDT0766:~$ gedit first.c
student@AUHDT0766:~$ gcc -o first first.c
student@AUHDT0766:~$ ./first
The Volume of the cube is: 960
Program 3: Program to Print Sum of all Even
Numbers from 1 to N
#include<stdio.h>
int main()
{
int i, number, Sum = 0;
printf("n Please Enter the Maximum Limit Value : ");
scanf("%d", &number);
printf("n Even Numbers between 0 and %d are : ", number);
for(i = 1; i <= number; i++)
{
if ( i%2 == 0 ) //Check whether remainder is 0 or not
{
printf("%d ", i);
Sum = Sum + i;
}
}
printf("n The Sum of All Even Numbers upto %d = %d", number, Sum);
return 0;
}
Program 3: Program to Print Sum of all Even
Numbers from 1 to N
student@AUHDT0766:~$ gedit second.c
student@AUHDT0766:~$ gcc -o second second.c
student@AUHDT0766:~$ ./second
Please Enter the Maximum Limit Value : 67
Even Numbers between 0 and 67 are : 2 4 6 8 10 12 14 16 18 20
22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60
62 64 66
The Sum of All Even Numbers upto 67 = 1122
Program 4: Program to Reverse a Number
using a while loop
#include <stdio.h>
int main()
{
int Number, Reminder, Reverse = 0;
printf("nPlease Enter any number to Reversen");
scanf("%d", & Number);
while (Number > 0)
{
Reminder = Number %10;
Reverse = Reverse *10+ Reminder;
Number = Number /10;
}
printf("Reverse of entered number is = %dn", Reverse);
return 0;
}
Program 4: Program to Reverse a Number
using a while loop
student@AUHDT0766:~$ gedit rev.c
student@AUHDT0766:~$ gcc -o rev rev.c
student@AUHDT0766:~$ ./rev
Please Enter any number to Reverse
78
Reverse of entered number is = 87
student@AUHDT0766:~$ ./rev
Please Enter any number to Reverse
678459
Reverse of entered number is = 954876
Program 5: Program to add two numbers using
function
#include<stdio.h>
int add (int x, int y);
int main() {
int a, b, result;
printf("Enter First Number");
scanf("%d",&a);
printf("Enter Second Number");
scanf("%d",&b);
result = add(a, b);
printf("%d + %d = %dn", a, b, result);
return 0; }
int add (int x, int y) {
x += y;
return(x);
}
Program 5: Program to add two numbers using
function
student@AUHDT0766:~$ gedit fadd.c
student@AUHDT0766:~$ gcc -o fadd fadd.c
student@AUHDT0766:~$ ./fadd
Enter First Number45
Enter Second Number23
45 + 23 = 68
Program 6: Factorial of a Number Using
Recursion
#include<stdio.h>
long int multiplyNumbers(int n);
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}
long int multiplyNumbers(int n) {
if (n>=1)
return n*multiplyNumbers(n-1);
else
return 1;
}
Program 6: Factorial of a Number Using
Recursion
student@AUHDT0766:~$ gedit fact.c
student@AUHDT0766:~$ gcc -o fact fact.c
student@AUHDT0766:~$ ./fact
Enter a positive integer: 8
Factorial of 8 = 40320
Fork System Call in C
•Fork system call is used for creating a new process, which is
called child process.
•It runs concurrently with the process that makes the fork() call
(parent process).
•After a new child process is created, both processes will
execute the next instruction following the fork() system call.
•A child process uses the same pc(program counter), same CPU
registers, same open files which use in the parent process.
Fork System Call in C
Fork System Call in C
fork() takes no parameters and returns an integer value.
Below are different values returned by fork().
•Negative Value: creation of a child process was unsuccessful.
•Zero: Returned to the newly created child process.
•Positive value: Returned to parent or caller.
The value contains process ID of newly created child process.
The syntax of the fork() system function is as follows:
pid_t fork(void);
Fork System Call in C
The fork() system function does not accept any
argument. It returns an integer of the type pid_t.
The pid_t data type represents process IDs.
You can get the process ID of a process by calling getpid.
On success, fork() returns the PID of the child process
which is greater than 0. Inside the child process, the
return value is 0. If fork() fails, then it returns -1.
Important Header Files
sys/types.h: Defines data types used in system source
code.
They can be used to enhance portability across different
machines and operating systems.
unistd.h: Defines miscellaneous symbolic constants and
types, and declares miscellaneous functions like version
constant etc.
sys/wait.h: declarations for waiting
Fork System Call in C
//Predict the Output of the following program:.
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
// make two process which run same
// program after this instruction
fork();
printf("Hello world!n");
return 0;
}
Fork System Call in C
Output:
student@AUHDT0766:~$ gedit forksys.c
student@AUHDT0766:~$ gcc -o forksys forksys.c
student@AUHDT0766:~$ ./forksys
Hello world!
Hello world!
The number of times ‘hello’ is printed is equal to
number of process created. Total Number of Processes
= 2n, where n is number of fork system calls.
Hence, 21=2 in above program.
PROGRAM FOR SYSTEM CALLS OF UNIX OPERATING
SYSTEM (fork, getpid, exit)
ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare the variables pid,pid1,pid2.
STEP 3: Call fork() system call to create process.
STEP 4: If pid==-1, exit.
STEP 5: Ifpid!=-1 , get the process id using getpid().
STEP 6: Print the process id.
STEP 7:Stop the program
PROGRAM FOR SYSTEM CALLS OF UNIX OPERATING
SYSTEM (fork, getpid, exit)
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
int pid,pid1,pid2;
pid=fork();
if(pid==-1)
{
printf("error in process creation");
exit(1);
}
PROGRAM FOR SYSTEM CALLS OF UNIX OPERATING
SYSTEM (fork, getpid, exit)
if(pid==0)
{
pid1=getpid();
printf("n the parent process id is %dn",pid1);
}
else
{
pid2=getpid();
printf("n the child process ID is %dn",pid2);
}
}
PROGRAM FOR SYSTEM CALLS OF UNIX OPERATING
SYSTEM (fork, getpid, exit)
student@AUHDT0766:~$ gedit fork2.c
student@AUHDT0766:~$ gcc -o fork2 fork2.c
student@AUHDT0766:~$ ./fork2
the child process ID is 4005
the parent process id is 4006
PROGRAM FOR SYSTEM CALLS OF UNIX
OPERATING SYSTEMS (OPENDIR, READDIR,
CLOSEDIR)
ALGORITHM:
STEP 1: Start the program.
STEP 2: Create Struct dirent.
STEP 3: declare the variable buff and pointer dptr.
STEP 4: Get the directory name.
STEP 5:Open the directory.
STEP 6: Read the contents in directory and print it.
STEP 7: Close the directory.
PROGRAM FOR SYSTEM CALLS OF UNIX
OPERATING SYSTEMS (OPENDIR, READDIR,
CLOSEDIR)
Data Type: struct dirent
This is a structure type used to return information about directory
entries.
It contains directory/file name, file serial number, length etc.
PROGRAM FOR SYSTEM CALLS OF UNIX OPERATING
SYSTEMS (OPENDIR, READDIR, CLOSEDIR)
#include<stdio.h>
#include<dirent.h>
#include<stdlib.h>
struct dirent *dptr;
int main()
{
char buff[100];
DIR *dirp;
printf("enter dir name");
scanf("%s", buff);
PROGRAM FOR SYSTEM CALLS OF UNIX OPERATING
SYSTEMS (OPENDIR, READDIR, CLOSEDIR)
if((dirp=opendir(buff))==NULL)
{
printf("the given directory does not exist.");
exit(1);
}
while(dptr=readdir(dirp))
{
printf("%sn",dptr->d_name);
}
closedir(dirp);
}
}
}
PROGRAM FOR SYSTEM CALLS OF UNIX OPERATING
SYSTEMS (OPENDIR, READDIR, CLOSEDIR)
Before running the above program you must have some directory
with further subdirectories and files in it. If you already use that
directory else create new as given below.
student@AUHDT0766:~$ mkdir ch
student@AUHDT0766:~$ cd ch
student@AUHDT0766:~/ch$ ls
student@AUHDT0766:~/ch$ mkdir dir1 dir2 dir3
tudent@AUHDT0766:~/ch$ ls
dir1 dir2 dir3
student@AUHDT0766:~/ch$ cat > file1
Hello Everyone.
student@AUHDT0766:~/ch$ cd ..
PROGRAM FOR SYSTEM CALLS OF UNIX OPERATING
SYSTEMS (OPENDIR, READDIR, CLOSEDIR)
Running the Program:
student@AUHDT0766:~$ gedit dir1.c
student@AUHDT0766:~$ gcc -o dir1 dir1.c
Output:
student@AUHDT0766:~$ ./dir1
enter dir name ch
dir1
dir2
.
file1
..
dir3
student@AUHDT0766:~$ ./dir1
enter dir name
nn
the given directory does not exist.

Weitere ähnliche Inhalte

Ähnlich wie Linux_C_LabBasics.ppt

Datastructure notes
Datastructure notesDatastructure notes
Datastructure notes
Srikanth
 
Lab report 201001067_201001104
Lab report 201001067_201001104Lab report 201001067_201001104
Lab report 201001067_201001104
swena_gupta
 
Lab report 201001067_201001104
Lab report 201001067_201001104Lab report 201001067_201001104
Lab report 201001067_201001104
swena_gupta
 
Lab report 201001067_201001104
Lab report 201001067_201001104Lab report 201001067_201001104
Lab report 201001067_201001104
swena_gupta
 
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
eugeniadean34240
 

Ähnlich wie Linux_C_LabBasics.ppt (20)

UNIT-II CP DOC.docx
UNIT-II CP DOC.docxUNIT-II CP DOC.docx
UNIT-II CP DOC.docx
 
Functions
FunctionsFunctions
Functions
 
Datastructure notes
Datastructure notesDatastructure notes
Datastructure notes
 
C-LOOP-Session-2.pptx
C-LOOP-Session-2.pptxC-LOOP-Session-2.pptx
C-LOOP-Session-2.pptx
 
Cinfo
CinfoCinfo
Cinfo
 
Lab report 201001067_201001104
Lab report 201001067_201001104Lab report 201001067_201001104
Lab report 201001067_201001104
 
Lab report 201001067_201001104
Lab report 201001067_201001104Lab report 201001067_201001104
Lab report 201001067_201001104
 
Lab report 201001067_201001104
Lab report 201001067_201001104Lab report 201001067_201001104
Lab report 201001067_201001104
 
C lab
C labC lab
C lab
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
Compiler design lab
Compiler design labCompiler design lab
Compiler design lab
 
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
 
C++ manual Report Full
C++ manual Report FullC++ manual Report Full
C++ manual Report Full
 
'C' language notes (a.p)
'C' language notes (a.p)'C' language notes (a.p)
'C' language notes (a.p)
 
B.Com 1year Lab programs
B.Com 1year Lab programsB.Com 1year Lab programs
B.Com 1year Lab programs
 
C programming Lab 2
C programming Lab 2C programming Lab 2
C programming Lab 2
 
Best C Programming Solution
Best C Programming SolutionBest C Programming Solution
Best C Programming Solution
 
Hargun
HargunHargun
Hargun
 
Core programming in c
Core programming in cCore programming in c
Core programming in c
 
C programs
C programsC programs
C programs
 

Kürzlich hochgeladen

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
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
MsecMca
 

Kürzlich hochgeladen (20)

Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
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
 
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 ...
 
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
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
(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
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
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
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
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
 

Linux_C_LabBasics.ppt

  • 2. Contents •Steps to write C programs on Terminal •C Basic programs
  • 3. Steps to write C programs on Terminal • Open terminal : Press Ctrl+Alt+T: Ubuntu/Linux terminal shortcut • On shell prompt type as below: $gedit filename.c •This will start the gedit text editor. • In editor type your program, save it and close editor.
  • 4. Steps to write C programs on Terminal • On shell prompt type: gcc –o filename filename.c • gcc, normally does preprocessing, compilation, assembly and linking. • This will create object file. gcc -o writes the build output to an output file. • Now type : ./filename for execution
  • 5. Program 1: To find average of two numbers #include <stdio.h> int main() { int number1, number2; float res; printf("Enter the First Number to find = "); scanf("%d",&number1); printf("Enter the Second Number to find = "); scanf("%d",&number2); int sm = number1 + number2; res = sm/2; //(float)sum/2; printf("The Sum of %d and %d = %dn", number1, number2, sm); printf("The Average of %d and %d = %.2fn", number1, number2, res); return 0; }
  • 6. Program 1: To find average of two numbers Steps to run C program on Ubuntu student@AUHDT0766:~$ gedit add1.c student@AUHDT0766:~$ gcc -o add1 add1.c student@AUHDT0766:~$ ./add1 Enter the First Number to find = 23 Enter the Second Number to find = 45 The Sum of 23 and 45 = 68 The Average of 23 and 45 = 34.00 student@AUHDT0766:~$
  • 7. Program 2: To find Volume of a Cube #include<stdio.h> void main() {//start the program int h,w,d,vol;//variables declaration h=10;w=12;d=8;//assign value to variables vol=h*w*d;//calculation usingmathematical formula printf("The Volume of the cube is: %d",vol);//display the volume return ; //end the main program }
  • 8. Program 2: : To find Volume of a Cube student@AUHDT0766:~$ gedit first.c student@AUHDT0766:~$ gcc -o first first.c student@AUHDT0766:~$ ./first The Volume of the cube is: 960
  • 9. Program 3: Program to Print Sum of all Even Numbers from 1 to N #include<stdio.h> int main() { int i, number, Sum = 0; printf("n Please Enter the Maximum Limit Value : "); scanf("%d", &number); printf("n Even Numbers between 0 and %d are : ", number); for(i = 1; i <= number; i++) { if ( i%2 == 0 ) //Check whether remainder is 0 or not { printf("%d ", i); Sum = Sum + i; } } printf("n The Sum of All Even Numbers upto %d = %d", number, Sum); return 0; }
  • 10. Program 3: Program to Print Sum of all Even Numbers from 1 to N student@AUHDT0766:~$ gedit second.c student@AUHDT0766:~$ gcc -o second second.c student@AUHDT0766:~$ ./second Please Enter the Maximum Limit Value : 67 Even Numbers between 0 and 67 are : 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 The Sum of All Even Numbers upto 67 = 1122
  • 11. Program 4: Program to Reverse a Number using a while loop #include <stdio.h> int main() { int Number, Reminder, Reverse = 0; printf("nPlease Enter any number to Reversen"); scanf("%d", & Number); while (Number > 0) { Reminder = Number %10; Reverse = Reverse *10+ Reminder; Number = Number /10; } printf("Reverse of entered number is = %dn", Reverse); return 0; }
  • 12. Program 4: Program to Reverse a Number using a while loop student@AUHDT0766:~$ gedit rev.c student@AUHDT0766:~$ gcc -o rev rev.c student@AUHDT0766:~$ ./rev Please Enter any number to Reverse 78 Reverse of entered number is = 87 student@AUHDT0766:~$ ./rev Please Enter any number to Reverse 678459 Reverse of entered number is = 954876
  • 13. Program 5: Program to add two numbers using function #include<stdio.h> int add (int x, int y); int main() { int a, b, result; printf("Enter First Number"); scanf("%d",&a); printf("Enter Second Number"); scanf("%d",&b); result = add(a, b); printf("%d + %d = %dn", a, b, result); return 0; } int add (int x, int y) { x += y; return(x); }
  • 14. Program 5: Program to add two numbers using function student@AUHDT0766:~$ gedit fadd.c student@AUHDT0766:~$ gcc -o fadd fadd.c student@AUHDT0766:~$ ./fadd Enter First Number45 Enter Second Number23 45 + 23 = 68
  • 15. Program 6: Factorial of a Number Using Recursion #include<stdio.h> long int multiplyNumbers(int n); int main() { int n; printf("Enter a positive integer: "); scanf("%d",&n); printf("Factorial of %d = %ld", n, multiplyNumbers(n)); return 0; } long int multiplyNumbers(int n) { if (n>=1) return n*multiplyNumbers(n-1); else return 1; }
  • 16. Program 6: Factorial of a Number Using Recursion student@AUHDT0766:~$ gedit fact.c student@AUHDT0766:~$ gcc -o fact fact.c student@AUHDT0766:~$ ./fact Enter a positive integer: 8 Factorial of 8 = 40320
  • 17. Fork System Call in C •Fork system call is used for creating a new process, which is called child process. •It runs concurrently with the process that makes the fork() call (parent process). •After a new child process is created, both processes will execute the next instruction following the fork() system call. •A child process uses the same pc(program counter), same CPU registers, same open files which use in the parent process.
  • 19. Fork System Call in C fork() takes no parameters and returns an integer value. Below are different values returned by fork(). •Negative Value: creation of a child process was unsuccessful. •Zero: Returned to the newly created child process. •Positive value: Returned to parent or caller. The value contains process ID of newly created child process. The syntax of the fork() system function is as follows: pid_t fork(void);
  • 20. Fork System Call in C The fork() system function does not accept any argument. It returns an integer of the type pid_t. The pid_t data type represents process IDs. You can get the process ID of a process by calling getpid. On success, fork() returns the PID of the child process which is greater than 0. Inside the child process, the return value is 0. If fork() fails, then it returns -1.
  • 21. Important Header Files sys/types.h: Defines data types used in system source code. They can be used to enhance portability across different machines and operating systems. unistd.h: Defines miscellaneous symbolic constants and types, and declares miscellaneous functions like version constant etc. sys/wait.h: declarations for waiting
  • 22. Fork System Call in C //Predict the Output of the following program:. #include <stdio.h> #include <sys/types.h> #include <unistd.h> int main() { // make two process which run same // program after this instruction fork(); printf("Hello world!n"); return 0; }
  • 23. Fork System Call in C Output: student@AUHDT0766:~$ gedit forksys.c student@AUHDT0766:~$ gcc -o forksys forksys.c student@AUHDT0766:~$ ./forksys Hello world! Hello world! The number of times ‘hello’ is printed is equal to number of process created. Total Number of Processes = 2n, where n is number of fork system calls. Hence, 21=2 in above program.
  • 24. PROGRAM FOR SYSTEM CALLS OF UNIX OPERATING SYSTEM (fork, getpid, exit) ALGORITHM: STEP 1: Start the program. STEP 2: Declare the variables pid,pid1,pid2. STEP 3: Call fork() system call to create process. STEP 4: If pid==-1, exit. STEP 5: Ifpid!=-1 , get the process id using getpid(). STEP 6: Print the process id. STEP 7:Stop the program
  • 25. PROGRAM FOR SYSTEM CALLS OF UNIX OPERATING SYSTEM (fork, getpid, exit) #include<stdio.h> #include<unistd.h> #include<stdlib.h> int main() { int pid,pid1,pid2; pid=fork(); if(pid==-1) { printf("error in process creation"); exit(1); }
  • 26. PROGRAM FOR SYSTEM CALLS OF UNIX OPERATING SYSTEM (fork, getpid, exit) if(pid==0) { pid1=getpid(); printf("n the parent process id is %dn",pid1); } else { pid2=getpid(); printf("n the child process ID is %dn",pid2); } }
  • 27. PROGRAM FOR SYSTEM CALLS OF UNIX OPERATING SYSTEM (fork, getpid, exit) student@AUHDT0766:~$ gedit fork2.c student@AUHDT0766:~$ gcc -o fork2 fork2.c student@AUHDT0766:~$ ./fork2 the child process ID is 4005 the parent process id is 4006
  • 28. PROGRAM FOR SYSTEM CALLS OF UNIX OPERATING SYSTEMS (OPENDIR, READDIR, CLOSEDIR) ALGORITHM: STEP 1: Start the program. STEP 2: Create Struct dirent. STEP 3: declare the variable buff and pointer dptr. STEP 4: Get the directory name. STEP 5:Open the directory. STEP 6: Read the contents in directory and print it. STEP 7: Close the directory.
  • 29. PROGRAM FOR SYSTEM CALLS OF UNIX OPERATING SYSTEMS (OPENDIR, READDIR, CLOSEDIR) Data Type: struct dirent This is a structure type used to return information about directory entries. It contains directory/file name, file serial number, length etc.
  • 30. PROGRAM FOR SYSTEM CALLS OF UNIX OPERATING SYSTEMS (OPENDIR, READDIR, CLOSEDIR) #include<stdio.h> #include<dirent.h> #include<stdlib.h> struct dirent *dptr; int main() { char buff[100]; DIR *dirp; printf("enter dir name"); scanf("%s", buff);
  • 31. PROGRAM FOR SYSTEM CALLS OF UNIX OPERATING SYSTEMS (OPENDIR, READDIR, CLOSEDIR) if((dirp=opendir(buff))==NULL) { printf("the given directory does not exist."); exit(1); } while(dptr=readdir(dirp)) { printf("%sn",dptr->d_name); } closedir(dirp); } } }
  • 32. PROGRAM FOR SYSTEM CALLS OF UNIX OPERATING SYSTEMS (OPENDIR, READDIR, CLOSEDIR) Before running the above program you must have some directory with further subdirectories and files in it. If you already use that directory else create new as given below. student@AUHDT0766:~$ mkdir ch student@AUHDT0766:~$ cd ch student@AUHDT0766:~/ch$ ls student@AUHDT0766:~/ch$ mkdir dir1 dir2 dir3 tudent@AUHDT0766:~/ch$ ls dir1 dir2 dir3 student@AUHDT0766:~/ch$ cat > file1 Hello Everyone. student@AUHDT0766:~/ch$ cd ..
  • 33. PROGRAM FOR SYSTEM CALLS OF UNIX OPERATING SYSTEMS (OPENDIR, READDIR, CLOSEDIR) Running the Program: student@AUHDT0766:~$ gedit dir1.c student@AUHDT0766:~$ gcc -o dir1 dir1.c Output: student@AUHDT0766:~$ ./dir1 enter dir name ch dir1 dir2 . file1 .. dir3 student@AUHDT0766:~$ ./dir1 enter dir name nn the given directory does not exist.