Ex.2-System Calls
Ex.2-System Calls
Ex.2-System Calls
#include<stdio.h>
#include<unistd.h>
main()
{
int pid,pid1,pid2;
pid=fork();
if(pid==-1)
{
printf(“ERROR IN PROCESS CREATION”);
exit(1);
}
if(pid!=0)
{
pid1=getpid();
printf(“THE PARENT PROCESS ID IS: %d”, pid1);
}
else
{
pid2=getpid();
printf(“THE CHILD PROCESS ID IS: %d”, pid2);
}
}
OUTPUT:
Output
$ gcc wait.c
$ ./a.out
Child starts
Odd Nos: 1 3 5 7 9
Child ends
Parent starts
Even Nos: 2 4 6 8 10
Parent ends
exec system call
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
int main()
{
pid_t pid;
switch(pid = fork())
{
case -1:
perror("Fork failed");
exit(-1);
case 0:
printf("Child process\n");
execl("/bin/date", "date", 0);
exit(0);
default: wait(NULL);
printf("Child Terminated\n");
exit(0);
}
}
Output
$ gcc exec.c
$ ./a.out
Child process Sat Feb 23 17:46:59 IST 2013
Child Terminated
stat system call
#include<stdio.h>
#include<stat.h>
#include<stdlib.h>
#include<time.h>
int main(int argc, char*argv[])
struct stat file;
int n;
if (argc != 2)
{
printf("Usage: ./a.out \n");
exit(-1);
}
if ((n = stat(argv[1], &file)) == -1)
{
perror(argv[1]);
exit(-1);
}
printf("User id : %d\n", file.st_uid);
printf("Group id : %d\n", file.st_gid);
printf("Block size : %d\n", file.st_blksize);
printf("Blocks allocated : %d\n", file.st_blocks);
printf("Inode no. : %d\n", file.st_ino);
printf("Last accessed : %s", ctime(&(file.st_atime)));
printf("Last modified : %s", ctime(&(file.st_mtime)));
printf("File size : %d bytes\n", file.st_size);
printf("No. of links : %d\n", file.st_nlink);
printf("Permissions : ");
printf( (S_ISDIR(file.st_mode)) ? "d" : "-");
printf( (file.st_mode & S_IRUSR) ? "r" : "-");
printf( (file.st_mode & S_IWUSR) ? "w" : "-");
printf( (file.st_mode & S_IXUSR) ? "x" : "-");
printf( (file.st_mode & S_IRGRP) ? "r" : "-");
printf( (file.st_mode & S_IWGRP) ? "w" : "-");
printf( (file.st_mode & S_IXGRP) ? "x" : "-");
printf( (file.st_mode & S_IROTH) ? "r" : "-");
printf( (file.st_mode & S_IWOTH) ? "w" : "-");
printf( (file.st_mode & S_IXOTH) ? "x" : "-");
printf("\n"); if(file.st_mode & S_IFREG);
printf("File type : Regular\n");
if(file.st_mode & S_IFDIR)
printf("File type : Directory\n");
}
Output:
$ gcc stat.c
$ ./a.out fork.c
User id : 0
Group id : 0
Block size : 4096
Blocks allocated : 8
Inode no. : 16627
Last accessed : Fri Feb 22 21:57:09 2013
Last modified : Fri Feb 22 21:56:13 2013
File size : 591 bytes
No. of links : 1
Permissions : -rw-r--r—
File type : Regular
readdir system call
#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
if (argc != 2)
{
printf("Usage: ./a.out <dirname>\n"); exit(-1);
}
while(dptr=readdir(dname))
printf("%s", dptr->d_name);
closedir(dname);
}
Output
$ gcc dirlist.c
$ ./a.out Sam
wait.c
a.out
..
stat.c
dirlist.c
fork.c
.
exec.c
open system call
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
#include <fcntl.h>
Output
$ gcc fcreate.c