Header Ads Widget

Ticker

6/recent/ticker-posts

Write a program which demonstrate the use of fork, join, and exec and wait system calls.

 #include <stdio.h>

#include <unistd.h>
#include <sys/wait.h>

int main() {
    pid_t pid;
    int status;

    pid = fork();  // Create a child process

    if (pid == 0) {  // Child process
        printf("Child process started\n");
        printf("Executing command using exec system call\n");
        char *args[] = { "/bin/ls", "-l", NULL };
        execv("/bin/ls", args);  // Execute the ls command
        printf("This line should not be printed\n");
    }
    else if (pid > 0) {  // Parent process
        printf("Parent process waiting for child to complete\n");
        wait(&status);  // Wait for child to complete
        printf("Child process exited with status %d\n", WEXITSTATUS(status));
    }
    else {  // Fork failed
        printf("Fork failed\n");
        return 1;
    }

    return 0;
}

Explanation:

The fork() system call is used to create a child process.
If fork() returns 0, then the code inside the if block is executed by the child process.
If fork() returns a positive value, then the code inside the else if block is executed by the parent process.
If fork() returns a negative value, then the code inside the else block is executed to indicate an error.
In the child process, the printf() function is used to print a message indicating that the child process has started.
The execv() system call is used to execute the ls -l command.
If the execv() system call is successful, then the code after it will not be executed. If it fails, then the error message will be printed.
In the parent process, the printf() function is used to print a message indicating that the parent process is waiting for the child to complete.
The wait() system call is used to wait for the child process to complete.
The WEXITSTATUS() macro is used to extract the exit status of the child process.
The exit status is printed using printf().

Post a Comment

0 Comments