Showing posts with label exit. Show all posts
Showing posts with label exit. Show all posts

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 - open, read, write, close, exit



// Unix system calls
// open, read, write, close system calls

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

int main (int argc, char *argv[])
{
        int fd;
        int n_char=0;
              char buffer[10];

        fd=open(argv[1],O_RDONLY);
        if (fd==-1)
        {
                   printf("File open error.");
                   exit(1);
        }

       
        while( (n_char=read(fd, buffer, 1))!=0)
                   n_char=write(1,buffer,n_char);
       
        close(fd)
        return 0;
}

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