System Calls in Unix and Windows
Total Page:16
File Type:pdf, Size:1020Kb
System Calls in Purpose of this Lecture Unix and Windows To familiarize you with using system calls – especially the ones to do with accessing and manipulating files. Will be of use later in the semester! Vivek Vishnumurthy 1 2 Roadmap What are System Calls? File manipulations: The services provided by the kernel to – open,close,creat,rename application programs. – read, write, lseek This interface is needed because there Directory manipulations: are things (eg: I/O instructions) that only – chdir, mkdir the kernel is allowed to perform. – link, unlink stdin, stdout, stderr 3 4 Roadmap… But first, the Shell Processes: The shell provides a user interface to – getpid,execl,fork the system. Other: – Often referred to as the “command-line – time interpreter” – But could be a GUI as well! – Egs: bash, csh, … 5 6 1 Issuing a System Call – Linux System Calls (about 300?) Normal Procedure: _llseek _newselec _sysctl accept access acct adjtimex afs_syscal alarm alloc_huge arch_prctl bdflush bind break brk cacheflush capget capset chdir chmod chown chroot clone close connect creat create_mo delete_moddup dup2 epoll_createpoll_ctl epoll_wait execve fchdir fchmod fchown fcntl fdatasync flock fork free_hugepfstat fstatfs fstatvfs fsync ftruncate futex get_kernel_get_thread_ In Unix: each system call is typically defined getcontext getdents getdomainngetdtablesigetegid geteuid getgid getgroups gethostid gethostnam getitimer getpagesizgetpeernamgetpgid getpgrp getpid getpmsg getppid getpriority getresgid getresuid getrlimit getrusage getsid getsocknamgetsockoptgettid gettimeofdagetuid gtty as a function in the standard C library. idle inb inb_p init_moduleinl inl_p insb insl insw intro inw inw_p io_cancel io_destroy io_geteven io_setup io_submit ioctl ioctl_list ioperm iopl ipc kill killpg lchown link listen llseek lock lookup_dco User process calls this function (in the normal lseek lstat madvise mincore mkdir mknod mlock mlock.2 mlockall mlockall.2 mmap mmap2 modify_ldt mount mprotect mpx mremap msgctl msgget msgop msgrcv msgsnd msync munlock munlockall munmap nanosleep nfsservctl nice obsolete C fashion) oldfstat oldlstat oldoldunamoldstat olduname open outb outb_p outl outl_p outsb outsl outsw outw outw_p pause pciconfig_i pciconfig_rpciconfig_wpersonality pipe pivot_root poll posix_fadvi prctl pread prof pselect ptrace putpmsg The function then invokes appropriate kernel pwrite query_modquotactl read readahead readdir readlink readv reboot recv recvfrom recvmsg rename rmdir sbrk sched_get_sched_get_sched_getasched_getpsched_gets service. sched_rr_gsched_setasched_setpsched_setssched_yiel security select select_tut semctl semget semop semtimedosend sendfile sendmsg sendto set_thread_setcontext setdomainnsetegid seteuid setfsgid setfsuid setgid setgroups sethostid sethostnamsetitimer setpgid setpgrp Use “man callname" for info about the call. setpriority setregid setresgid setresuid setreuid setrlimit setsid setsockoptsettimeofdasetuid setup sgetmask shmat shmctl shmdt shmget shmop shutdown sigaction sigaltstack sigblock siggetmasksigmask signal sigpause sigpending sigprocmassigqueue sigreturn sigsetmask sigsuspendsigtimedwasigvec sigwaitinfo socket socketcall socketpair ssetmask stat statfs “man –s 2 callname” in Solaris. statvfs stime stty swapoff swapon symlink sync syscall syscalls sysctl sysfs sysinfo syslog time times tkill truncate umask umount umount2 uname undocumenunimplemeunlink uselib ustat utime utimes vfork vhangup “man –S 2 callname” or just vm86 wait wait3 wait4 waitpid write writev “man callname” in Linux. 7 8 Issuing SysCall in Unix… In C#/Windows? #include <lib-file.h> “The Windows API” Lib file that has – (Comparatively) larger number of function calls. function declaration We will just concentrate on how to issue File syscall-name(); I/O calls in C#. These calls are implemented in the System.IO namespace. SysCall being called In VS .NET : see help on members of System.IO.File and System.IO.FileStream 9 10 So, in C#… File Manipulation using System.IO ; File Descriptors in Unix Namespace that has File Streams in C# method declaration method-name(); These are basically identifiers of a file opened for data access. – Support reading from files. File Method – Support writing to files. being called – Support seeking – changing position within the stream. 11 12 2 open (an exisiting file) in C/Unix open (an exisiting file) in C# using System.IO; #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> // open file 'test' for reading and writing Stream fstream = File.Open("test", System.IO.FileMode.Open, // open file 'test' for reading and writing System.IO.FileAccess.ReadWrite); int fdtest = open("test", O_RDWR); This is the option that sets file manipulation permissions – It’s the optionWhat’s that this? sets file manipulation permissions – See VS .NET help on “FileAccess” for more info Run “man 2 open” for more info 13 14 close (an already opened create (a new file) descriptor or stream) C/Unix: C#: #include <sys/types.h> using System.IO; C/Unix: C#: #include <sys/stat.h> #include <unistd.h> using System.IO; #include <fcntl.h> //close opened descriptor //create newFile with read, //create file newFile int closeResult = //close opened stream close(fdtest); //write, execute permissions Stream fstream = fstream.Close(); if(closeResult==0){ int newfd = creat(“newFile”, File.Create(“newFile"); S_IRWXU); printf("Closed successfully\n"); }else{ This is the option that sets printf("Close failed\n"); required access permissions – } Run “man creat” for more info 15 16 read (from an opened file) write (to file) #include <unistd.h> using System.IO; C/Unix: #include <unistd.h> //for write #include <string.h> //for strlen int nBytes = 100; char buf[nBytes] ; byte[] bytes = new byte[100]; char buf[] = “Hello World!\n”; //read upto ‘nBytes’ bytes //read from file into 'bytes' int nBytes = strlen(buf); // from file into buf int nRead = fstream.Read( //write ‘nBytes’ bytes from buf int nRead = read(fd, buf, bytes, 0, nBytes); bytes.Length); //to the file int nWrote = write(fd,buf,nBytes); The number of bytes Number of bytes actually read written Opened descr. on file 17 18 3 write (to file) lseek in C/Unix C#: using System.IO; Repositions read/write position in file. Useful when (say) you want to read bytes 20- String buf = “Hello World!\n”; 29 from a file. byte[] bufBytes = new byte[buf.Length]; #include <sys/types.h> int nBytes = buf.Length; for(int i=0; i<nBytes; i++) #include <unistd.h> { bufBytes[i] = (byte)buf[i]; } //offset from start //write ‘nBytes’ bytes from bufBytes to file int offset = 20; fstream.Write(bufBytes, 0, nBytes); //reposition read/write position The offset is from the start of file. For other options: run “man lseek” lseek(fd, offset, SEEK_SET); char buf[10]; Offset from start #Bytes to write //read 10 bytes starting at offset read(fd, buf, 10); Opened stream on file 19 20 Seek in C# rename in C/Unix using System.IO; Used to change name/location of a file. #include <stdio.h> //offset from start int offset = 20; //rename file ‘oldfile’ to ‘newfile’ //reposition read/write position int resRename = rename(“oldfile", fstream.Seek(offset, System.IO.SeekOrigin.Begin); “newfile"); if(resRename==0){ byte[] bufBytes = new byte[10]; printf("rename successful\n"); //read 10 bytes starting at offset }else{ fstream.Read(bufBytes, 0, bufBytes.Length); printf("rename failed\n"); } The offset is from the start of file. For other options: see help on SeekOrigin in VS .NET 21 22 Directories: Move in C# chdir (C/Unix) Used to change name/location of a file. Change working directory. using System.IO; #include <unistd.h> //rename file ‘oldfile’ to ‘newfile’ File.Move(“oldfile", “newfile"); char newDir[] = “/usr/u/vivi/courses/414”; //change working directory to newDir chdir(newDir); 23 24 4 mkdir (C/Unix) link (C/Unix) Create new directory. Creates a new link (a hard link) to an existing file. #include <unistd.h> #include <unistd.h> char newDir[] = “/usr/u/vivi/courses/414”; mkdir(newDir, S_IRWXU); link(“oldfile", “newname"); This is the option that sets Both oldfile and newname now refer access permissions – Run “man creat” for more info to the same file. 25 26 Processes: unlink (C/Unix) getpid (C/Unix) Deletes a filename. Every process has a unique process ID. getpid()returns the value of the ID of the #include <unistd.h> calling process. unlink(“newname"); #include <unistd.h> #include <sys/types.h> If newname is the last link to the file, //get process ID of the process then file itself is deleted, else the link is int pid = getpid(); deleted. Used to generate unique temp file names. 27 28 execl (C/Unix) fork (C/Unix) Replace current process image with Creates a replica child process differing new process image. Arguments to the new only in pid and ppid(parent’s pid). process #include <unistd.h> #include <sys/types.h> #include <unistd.h> In parent, fork() returns child’s pid. In child, fork() returns 0. The last argument has execl("/bin/ls", "~", NULL); to be a null pointer If newname is the last link to the file, if(fork()==0) printf(“I am the child\n”); then file itself is deleted, else the link is else deleted. printf(“I am the parent\n”); 29 30 5 time (C/Unix) stdin/stdout/stderr (Unix) Get time in seconds - #seconds elapsed Are streams for Standard Input, Output and since 00:00:00 UTC, January 1, 1970. Error, respectively. #include <time.h> Each Unix program has these three streams opened for it. time_t elapsed = time(); Eg: When printf or putchar is called, the printf(“Time