==============================================================
Experiment 04: Process Creation Using fork(), execvp(), wait()
==============================================================
[Back to Index]
--------------------------------------------------------------
THEORY:
fork() - Creates a new child process (copy of parent).
Returns 0 to child, child PID to parent, -1 on fail.
execvp()- Replaces child process image with a new program.
wait() - Parent pauses until child finishes.
--------------------------------------------------------------
PROGRAM (a): fork() - Print Parent and Child PIDs
--------------------------------------------------------------
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid;
pid = fork();
if (pid < 0) {
perror("fork failed");
return 1;
}
if (pid == 0) {
// Child process
printf("Child Process:\n");
printf(" PID = %d\n", getpid());
printf(" PPID = %d\n", getppid());
} else {
// Parent process
printf("Parent Process:\n");
printf(" PID = %d\n", getpid());
printf(" Child PID = %d\n", pid);
}
return 0;
}
--------------------------------------------------------------
PROGRAM (b): myadder.c - Add two integers via command line
--------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: myadder <num1> <num2>\n");
return 1;
}
int a = atoi(argv[1]);
int b = atoi(argv[2]);
printf("Sum = %d\n", a + b);
return 0;
}
--------------------------------------------------------------
PROGRAM (b): execvp_demo.c - fork + execvp
--------------------------------------------------------------
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
pid_t pid = fork();
if (pid < 0) {
printf("Fork failed\n");
}
else if (pid == 0) {
// Child process
char *args[] = {"./myadder", "10", "20", NULL};
execvp(args[0], args);
// Executes only if execvp fails
printf("execvp failed\n");
}
else {
// Parent process
wait(NULL);
printf("Parent process completed\n");
}
return 0;
}
--------------------------------------------------------------
PROGRAM (c): fork + wait - Print "PCCSL407 Operating Systems Lab"
--------------------------------------------------------------
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid = fork();
if (pid < 0) {
perror("fork failed");
return 1;
}
if (pid == 0) {
// Child
printf("PCCSL407 ");
} else {
// Parent waits for child to finish
wait(NULL);
printf("Operating Systems Lab\n");
}
return 0;
}
--------------------------------------------------------------
==============================================================
[Prev: Exp 03] | [Next: Exp 05]
==============================================================