wait() command for synchronization

 

Aim:

To write a program that creates a new process using the fork() system call.
The child process should print the string "PCCSL407", and the parent process should print "Operating Systems Lab".
The wait() system call is used to ensure the output is displayed in the order:

PCCSL407 Operating Systems Lab

Theory:

In UNIX/Linux operating systems, the fork() system call is used to create a new process (child process) from the existing process (parent process).
After the call, both parent and child execute the same program code independently.

  • fork() returns:

    • 0 to the child process

    • Child’s PID (a positive integer) to the parent process

    • -1 on error

The wait() system call is used by a parent process to wait for the completion of its child process.
It helps to achieve process synchronization, ensuring that the parent executes its statements only after the child has finished execution.

By combining fork() and wait(), we can control the order in which output appears from both processes.


Algorithm:

  1. Start the program.

  2. Call the fork() system call to create a new process.

  3. If fork() returns a negative value, display an error message.

  4. If the return value is zero, it indicates the child process.

    • Print "PCCSL407".

  5. Otherwise, it is the parent process.

    • Call wait(NULL) to wait until the child process finishes.

    • Print "Operating Systems Lab".

  6. End the program.


Program:

#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> int main() { pid_t pid; pid = fork(); // Create a new process if (pid < 0) { perror("fork failed"); return 1; } else if (pid == 0) { // Child process printf("PCCSL407 "); } else { // Parent process waits for the child wait(NULL); printf("Operating Systems Lab\n"); } return 0; }

Output:

PCCSL407 Operating Systems Lab

Result:

The program was successfully executed and verified.
The fork() system call created a new process, and the wait() system call ensured that the parent process executed only after the child completed, producing the output in the desired order.

Comments

Popular posts from this blog

Operating Systems OS Lab PCCSL407 Semester 4 KTU BTech CS 2024 Scheme - Dr Binu V P

Exploring the /proc file system

ps command