0% found this document useful (0 votes)
123 views41 pages

System Calls

The document provides information on various C programming concepts related to system calls for file and directory operations. It discusses functions for opening, reading, writing, closing files and changing file permissions. It also covers functions for directory operations like opendir, readdir, stat, fstat for getting file information, lseek for changing file position, unlink for deleting files, and system calls for process operations like fork.

Uploaded by

Navdeep Walia
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
123 views41 pages

System Calls

The document provides information on various C programming concepts related to system calls for file and directory operations. It discusses functions for opening, reading, writing, closing files and changing file permissions. It also covers functions for directory operations like opendir, readdir, stat, fstat for getting file information, lseek for changing file position, unlink for deleting files, and system calls for process operations like fork.

Uploaded by

Navdeep Walia
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 41

C Programming

Open gedit Write program,save it with .c extension

$gcc o n nameofprog.c $./n

Functions used to access and controlling files and devices are called System Calls. Using it, we can open ,read, write device files in regular file way

Fcntl.h---file control options Unistd.h---contains system call number passed to kernel when system call is invoked Sys/types.h---contains defn of datatypes used in system calls Sys/stat.h----This function returns info about file like ID of device containing file,gid of owner, time of last access and last modification.

Low level functions used to access device drivers are: Open(const char*path,int oflags) Read(int filedes,void *buf,size_t nbytes) Write(int fildes,const void *buf,size_t nbytes) Close(int filedes) Lseek Fstat Stat Lstat

#include<unistd.h> #include<stdlib.h> Int main() { if((write(1,hello,5)!=5) Write(2,Error,5); Exit(0); }

Open(const char*path,int oflags) Int open(const char*path,int oflags,mode_t mode) Modes are Flags are S_IRUSR O_RDONLY,O_WRONLY S_IWGRP O_CREAT S_IXOTH O_RDWR,O_APPEND

#include <unistd.h> Int main() { Char buffer[128]; Int nread; nread = read(0 , buffer , 128); If (nread== -1) write(2, A read error has occurred\n, 26); If ((write(1,buffer,nread)) != nread) write(2, A write error has occurred\n, 27); exit(0); }

#include <unistd.h> #include <sys/stat.h> #include <fcntl.h> int main() { char c; int in, out; in = open(file.in, O_RDONLY); out = open(file.out, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR); while(read(in,&c,1) == 1) write(out,&c,1); exit(0); }

These functions return information about a file. No permissions are required on the file itself, but -- in the case of stat() and lstat() -- execute (search) permission is required on all of the directories in path that lead to the file.
stat() stats the file pointed to by path and fills in buf. lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to. fstat() is identical to stat(), except that the file to be stat-ed is specified by the file descriptor filedes.

All of these system calls return a stat structure, which contains the following fields:
struct stat { dev_t st_dev; /* ID of device containing file */ ino_t st_ino; /* inode number */ mode_t st_mode; /* protection */ nlink_t st_nlink; /* number of hard links */ uid_t st_uid; /* user ID of owner */ gid_t st_gid; /* group ID of owner */ dev_t st_rdev; /* device ID (if special file) */ off_t st_size; /* total size, in bytes */ blksize_t st_blksize; /* blocksize for filesystem I/O */ blkcnt_t st_blocks; /* number of blocks allocated */ time_t st_atime; /* time of last access */ time_t st_mtime; /* time of last modification */ time_t st_ctime; /* time of last status change */ };

Int main() { Struct stat b; Int status,in; In=open(a11,O_RDONLY); If(in!=-1) Printf(Success); Status=fstat(in,&b); If(status=0) Printf(Success); Printf(%d%d%d,b.st_ino,b.st_uid,b.st_gid); Return 0; }

used to change the location of the read/write pointer of a file descriptor. The location can be set either in absolute or relative terms.

off_t lseek(int fildes, off_t offset, int whence);


The offset parameter is used to specify the position, and the whence parameter specifies how the offset is used. whence can be one of the following: SEEK_SET: offset is an absolute position SEEK_CUR: offset is relative to the current position SEEK_END: offset is relative to the end of the file

#include<unistd.h> #include<fcntl.h> #include<sys/types.h> #include<stdio.h> int main() { int file=0; file=open("testfile.txt",O_RDONLY); char buffer[19]; lseek(file,10,SEEK_SET); if(read(file,buffer,19) != 19) return 1; printf("%s\n",buffer); return 0; }

Delete files The unlink may be used to delete a file (A file may have

multiple names (also called links), here we assume that a file in this context has only one name or link.). Its syntax is:

int unlink(const char *path); path is the file name to be deleted. The unlink system call returns the value 0 if

successful, otherwise it returns the value -1.

Chmod Chown Unlink Link Symlink Mkdir Rmdir Chdir getcwd

To change file access permissions


int chmod(const char *path, mode_t mode);

int main() { if(chmod("Example.txt" , 0444) < 0 ) { printf("change mode of file Example.txt failed \n"); return -1; } printf("Chmod system call successful \n"); return 0; }

int link(const char *name1, const char *name2) int symlink(const char *oldpath, const char *newpath);

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


int mkdir(const char *pathname, mode_t mode) mkdir() attempts to create a directory named pathname. E.g mkdir(/home/user/a,S_IRUSR|S_IWUSR)

rmdir - delete a directory #include <unistd.h>


int rmdir(const char *pathname); rmdir() deletes a directory, which must be empty. Rmdir(/home/user/a)

#include <unistd.h> int chdir(const char *path);


int fchdir(int fd); chdir() changes the current working directory to that specified in path.

#include <unistd.h> char *getcwd(char *buf, size_t size); The getcwd() function copies an absolute pathname of the current working directory to the array pointed to by buf, which is of length size.

#include <unistd.h> #include <stdio.h>


int main() { char cwd[1024]; if (getcwd(cwd, sizeof(cwd)) != NULL) fprintf(stdout, "Current working dir: %s\n", cwd); else perror("getcwd() error"); return 0; }

#include <sys/types.h> #include <unistd.h> int chown(const char *path, uid_t owner, gid_t group);

opendir closedir readdir telldir seekdir

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


uid_t getuid(void); char *getlogin(void); The getuid function returns the UID with which the program is associated. This is usually the UID of the user who started the program. The getlogin function returns the login name associated with the current user.
E.g It consists of lines, one per user, that contain the username, encrypted password, user identifier (UID), group identifier (GID), full name, home directory, and default shell. Heres an example line: neil:zBqxfqedfpk:500:100:Neil Matthew:/home/neil:/bin/bash

#include <sys/types.h> #include <pwd.h> struct passwd *getpwuid(uid_t uid); struct passwd *getpwnam(const char *name); passwdMember Description char *pw_name The users login name uid_t pw_uid The UID number gid_t pw_gid The GID number char *pw_dir The users home directory char *pw_gecos The users full name char *pw_shell The users default shell

int main() { uid_t uid; gid_t gid; struct passwd *pw; uid = getuid(); gid = getgid(); printf(User is %s\n, getlogin()); printf(User IDs: uid=%d, gid=%d\n, uid, gid); pw = getpwuid(uid); printf(UID passwd entry:\n name=%s, uid=%d, gid=%d, home=%s, shell=%s\n, pw->pw_name, pw->pw_uid, pw->pw_gid, pw->pw_dir, pw->pw_shell); pw = getpwnam(root); printf(root passwd entry:\n); printf(name=%s, uid=%d, gid=%d, home=%s, shell=%s\n, pw->pw_name, pw->pw_uid, pw->pw_gid, pw->pw_dir, pw->pw_shell); exit(0); }

Fork():is used to create processes.


It takes no arguments and returns a process ID. The purpose of fork() is to create a new process, which becomes the child process of the caller. After a new child process is created, both processes will execute the next instruction following the fork() system call. Therefore, the parent and child processes have separate address spaces.

The dup system calls provide a way of duplicating a file descriptor, giving two or more different descriptors that access the same file The dup system call duplicates a file descriptor, filedes, returning a new descriptor The dup2 system call effectively copies one file descriptor to another by specifying to use for the copy. #include<unistd.h> Int dup(int filedes); Int dup2(int filedes, int filedes);

#include<unistd.h> #include<fcntl.h> #include<stdio.h> int main() { int fd,x,n; fd = open("testfile.txt", O_WRONLY |O_CREAT); printf("file desc is %d\n",fd); x=dup2(fd, 14); printf("\n new file desc is %d",x); n=dup(x); printf("\n another new fd is %d",n); }

#include<stdio.h> #include<errno.h> #include<fcntl.h> int main() { int y; size_t filedesc = open("xxyyzz", O_WRONLY); if (filedesc ==-1) { printf("File cannot be opened and file descriptor =%d\n",filedesc); y=errno; printf("errno value=%d\n",y); } else printf("File opened and file descriptor =%d\n",filedesc); return 0; }

#include<unistd.h> #include<fcntl.h> #include<sys/stat.h> #include<dirent.h> #include<stdio.h> #include<errno.h> int main() { int in,i; in=chmod("/home/u/1/chmod.txt",S_IRWXU|S_IRWXG); if (in ==-1) { printf ("cannot change permissions"); i=errno; printf (" permission change failed because of errno value= %d",i); } return 0; }

#include<unistd.h> #include<fcntl.h> #include<sys/stat.h> #include<dirent.h> #include<stdio.h> #include<errno.h> int main() { int in,i; in=chmod("/home/u/1/chmod.txt",0777); if (in ==-1) { printf ("cannot change permissions"); i=errno; printf (" permission change failed because of errno value= %d",i); } return 0; }

Open system call opens a directory. If successful it returns a pointer to dir structure to be used for reading directory entries.

#include<sys/types.h> #include<dirent.h> DIR *opendir(const char *name);

Readdir function returns a pointer to a structure detailing the next directory entry in the directory stream dirp.

#include<sys/types.h> #include<dirent.h> Struct dirent *readdir(DIR *dirp)

#include<stdio.h>
#include<dirent.h> #include<errno.h> int main() { struct dirent *dptr; char buff[256]; DIR *dirp; printf("\n\n Enter directory Name"); scanf("%s",buff); dirp=opendir(buff); if (dirp==NULL) { printf("Error openeing directory"); int z=errno; printf("errno value = %d ",z); } while(dptr=readdir(dirp)) {

printf("%s\n",dptr->d_name);
} closedir(dirp); }

The telldir function returns a position that records the current position in directory stream #include<sys/types.h> #include<dirent.h> Long int telldir(DIR *dirp); The seekdir function sets the directory entry pointer in the directory given by dirp. The value of loc, used to set the position should have been obtained from a prior call to telldir.

#include<unistd.h> #include<sys/stat.h> #include<sys/types.h> #include<dirent.h> int main() { DIR *d; struct dirent *dd; long tell; d=opendir("/home/baljit/.."); dd=readdir(d); printf("%s %d\n",dd->d_name,dd->d_ino); tell=telldir(d); dd=readdir(d); printf("%s %d\n", dd->d_name, dd->d_ino); seekdir(d,tell); dd=readdir(d); printf("%s %d\n",dd->d_name,dd->d_ino); }

You might also like