CSCI-332 Week2 2
CSCI-332 Week2 2
Operating Systems
int main()
int main()
{
{
fork();
fork();
fork();
fork();
printf("Hello world!\n"); printf("Hello world!\n");
return 0; return 0;
} }
What will be the output?
Hello from Child!
#include <stdio.h>
●
#include <sys/types.h>
#include <unistd.h> Hello from Parent!
void forkexample(){
if (fork() == 0)
printf("Hello from Child!\n");
●
Hello from Parent!
else Hello from Child!
printf("Hello from Parent!\n");
} ●
Any of the two
int main(){
forkexample();
return 0;
}
getpid() and getppid()
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int p = fork();
if ( p == 0 ) {
printf( "After the fork, the pid of the child is %d\n", getpid() );
} else {
printf( "After the fork, the pid of the parent is %d\n", getpid() );
}
return 0;
}
wait()
#include<stdio.h>
#include<sys/wait.h>
#include<unistd.h>
int main(){
int p = fork();
if (p == 0) {
printf("Hello from child\n");
sleep(2);
} else {
printf("Hello from parent\n");
wait(NULL);
printf("Child has terminated\n");
}
printf("Bye\n");
return 0;
}
exec() and wait()
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(){
char *argv[3] = {"Command", "-l", NULL};
int status = 1;
int p = fork();
if ( p == 0 ) {
execvp( "ls", argv );
}
wait( &status );
int main(){
int p = fork();
if (p == 0) {
printf("Hello from child\n");
sleep(2);
} else {
printf("Hello from parent\n");
wait(NULL);
printf("Child has terminated\n");
}
printf("Bye\n");
return 0;
}
Change the following code to create an
orphan process
#include<stdio.h>
#include<sys/wait.h>
#include<unistd.h>
int main(){
int p = fork();
if (p == 0) {
printf("Hello from child\n");
sleep(2);
} else {
printf("Hello from parent\n");
wait(NULL);
printf("Child has terminated\n");
}
printf("Bye\n");
return 0;
}
Any questions?
What to read
●
Re-run the examples and play with fork(),
exec(), wait() etc.
●
Read the documentation of those system calls
Next class
●
Friday: Lab about processes
– Have your VM or native Linux installation ready
– You will need to run some commands and develop
some code