Unix System Calls - fork, getpid, getppid

// System calls
// fork, exec, getpid, getppid, exit

#include<sys/types.h>   
#include<stdio.h>     
#include<unistd.h>
#include<sys/wait.h>
#include <stdlib.h>

int main()
{
    pid_t pid;
    
    /* fork a child process */
    pid = fork();
    
    if (pid < 0) 
        { 
            /* error occurred */
            fprintf(stderr, "Fork Failed");
            return 1;
    }
    else if (pid == 0) 
        {   
            /* child process */
            printf("\nExecuting in child process");
            printf("\n child process pid=%d ", getpid());
            printf("\n parent process pid=%d ", getppid());
            printf("\n Executing ls command.\n");
            execlp("/bin/ls","ls",NULL);
            exit(0);
    }
        else 
        { 
            /* parent process */
        /* parent will wait for the child to complete */
        printf("\nExecuting in parent process, pid=%d \n", getpid());
        wait(NULL);
        printf("Child Complete");
    }
    return 0;
}

No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu