<<

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 – ,,creat,rename application programs. – , , lseek „ This interface is needed because there „ Directory manipulations: are things (eg: I/O instructions) that only – chdir, 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, the system. „ Other: – Often referred to as the “command-line – interpreter” – But could be a GUI as well! – Egs: bash, csh, …

5 6

1 Issuing a System Call – 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 chown 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 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 . 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_list ioperm iopl ipc killpg lchown link listen llseek lock lookup_dco „ User calls this function (in the normal lseek lstat madvise mincore mkdir mknod mlock mlock.2 mlockall mlockall.2 mmap2 modify_ldt mount mprotect mpx mremap msgctl msgget msgop msgrcv msgsnd msync munlock munlockall munmap nanosleep nfsservctl 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 putpmsg „ The function then invokes appropriate kernel pwrite query_modquotactl read readdir readlink readv recv recvfrom recvmsg rename rmdir 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 sigpause sigpending sigprocmassigqueue sigreturn sigsetmask sigsuspendsigtimedwasigvec sigwaitinfo socket socketcall socketpair ssetmask statfs „ “man –s 2 callname” in Solaris. statvfs stime stty swapoff swapon symlink syscall syscalls 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 wait3 wait4 waitpid write writev “man callname” in Linux. 7 8

Issuing SysCall in Unix… In C#/Windows?

#include „ “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 #include #include

// 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); 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 using System.IO; C/Unix: C#: #include #include using System.IO; #include

//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 using System.IO; C/Unix: #include //for write #include //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 int nBytes = buf.Length; for(int i=0; i { 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 //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 . using System.IO;

#include //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 ) to an existing file. #include

#include 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 calling process.

unlink(“newname"); #include #include „ 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 #include #include 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 for Standard Input, Output and since 00:00:00 UTC, January 1, 1970. Error, respectively. #include „ Each Unix program has these three streams opened for it. time_t elapsed = time(); „ Eg: When printf or putchar is called, the printf(“Time elapsed = %ld\n”, elapsed); output goes to stdout. „ Similarly, when getchar or scanf is called, the input is from stdin. „ stderr used to output error messages.

31 32

stdin/stdout… Using for stdin/stdout… simpler File I/O „ Say a program writer writes out text, „ Say a program prog uses getchar. and program reader reads text. Then: „ The command-line $ writer | reader $ prog < infile causes prog to read its characters from causes reader to read characters infile, rather than the terminal. produced by writer. „ prog’s standard input stream now reads „ reader’s stdin is writer’s stdout. from infile. „ Examples taken from “The C Programming Language” by Brian W. Kernighan and Dennis M. Ritchie. „ Examples taken from “The C Programming Language” by Brian W. Kernighan and Dennis M. Ritchie.

33 34

Summary

„ We looked at how to use system calls and do File I/O. „ Use the man and the help pages extensively!

35

6