Assignment 6
Assignment 6
Processes
A collection of logical control flows called processes (task or jobs).In other word a process is a program
in execution.
Each process is an instance of a running program.
Fork():
int fork(void)
• creates a new process (child process) that is identical to the calling process (parent
process)
• returns 0 to the child process
• returns child‘s pid to the parent process
• Returns negetive value if t fails to create process.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
int pid;
// Create a new process
pid = fork();
if (pid < 0) {
// Error occurred
fprintf(stderr, "fork() failed\n");
exit(1);
}
// Child process
else if (pid == 0) {
printf("Child process ID: %d\n", getpid());
printf("Parent process ID: %d\n", getppid());
printf("This is the child process\n");
sleep(2);
printf("Child process exiting\n");
exit(0);
}
// Parent process
else {
printf("Parent process ID: %d\n", getpid());
printf("Child process ID: %d\n", pid);
printf("This is the parent process\n");
wait(NULL);
printf("Parent process exiting\n");
exit(0);
}
return 0;
}
Output:
Output: