Explain Output of Each Program
Explain Output of Each Program
Negative value to indicate an error, i.e., unsuccessful in creating the child process.
Returns a zero for child process.
Returns a positive value for the parent process. This value is the process ID of the
newly created child process.
int main() {
fork();
printf("Called fork() system call\n");
return 0;
}
Program 2
#include <stdio.h>
#include <unistd.h> // fork
int main() {
fork();
printf("Hello world -> My PID is %d\n", getpid());
return 0;
}
Program 3 : creation of process
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
pid_t pid;
pid = getpid();
printf("Before fork: Process id is %d\n", pid);
if (pid < 0) {
perror("fork() failure\n");
return 1;
}
// Child process
if (pid == 0) {
printf("This is child process\n");
} else { // Parent process
sleep(2);
printf("This is parent process\n");
}
return 0;
}
Program 4 : creation of process
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
pid_t pid, mypid, myppid;
pid = getpid();
printf("Before fork: Process id is %d\n", pid);
pid = fork();
if (pid < 0) {
perror("fork() failure\n");
return 1;
}
// Child process
if (pid == 0) {
printf("This is child process\n");
mypid = getpid();
myppid = getppid();
printf("Process id is %d and PPID is %d\n", mypid, myppid);
} else { // Parent process
sleep(2);
printf("This is parent process\n");
mypid = getpid();
myppid = getppid();
printf("Process id is %d and PPID is %d\n", mypid, myppid);
printf("Newly created process id or child pid is %d\n", pid);
}
return 0;
}
Program 5 : creation of process
#include <stdio.h>
#include <unistd.h> // fork
int main() {
printf("Program execution start here.\n");
int r = fork();
printf(
"Hello world -> My PID is %d, I am %s process\n",
getpid(),
r==0 ? "child" : "parent"
);
return 0;
}
Lab6: copy on write
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
void forkexample()
{
int x = 1;
pid_t p = fork();
if(p<0){
perror("fork fail");
exit(1);
}
else if (p == 0)
printf("Child has x = %d\n", ++x);
else
printf("Parent has x = %d\n", x);
}
int main()
{
forkexample();
return 0;
}
Program 7 : process termination