Showing posts with label getppid. Show all posts
Showing posts with label getppid. Show all posts

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;
}

Unix System Calls - wait exit exec

// Unix system calls
// exec, exit, wait

#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>

int main(int argc, char *argv[])
{
          pid_t pid;
          int cstatus;            
          pid_t c;                

          pid=fork();
         
          if(pid == -1)
                   printf("\n Error in creating process ");
          else if(pid == 0)
          {
                   printf("\nExecuting in child process");
                   execvp(argv[1], &argv[1]);
                    perror("exec failure");
                   exit(1);
          }
          else
          {
                    printf("\nExecuting in parent process");
                    c = wait(&cstatus); /* Wait for child to complete. */
                   printf("\nParent: Child %ld exited with status = %d\n", (long) c, cstatus);
          }       
}

Unix System Calls - stat


Unix System Calls

// Unix system calls
// stat

#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>

void main(int argc, char **argv)
{
    if(argc != 2)   
        printf("Usage error: Invalid number of arguments.");

    struct stat fs;
    if(stat(argv[1],&fs) < 0)   
        printf("Usage error: File / directory does not exist.");

    printf("Information for %s\n",argv[1]);
    printf("File Size: \t\t%d bytes\n",fs.st_size);
    printf("File inode: \t\t%d\n",fs.st_ino);
    printf("File mode: \t\t%d\n",fs.st_mode);
    printf("user ID of file owner: \t%d\n",fs.st_uid);
    printf("File last access time: \t%d\n",fs.st_atime);
    
}