Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
38 views29 pages

Linux Unit 1 And2

Uploaded by

Sarthi Darji
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views29 pages

Linux Unit 1 And2

Uploaded by

Sarthi Darji
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Linux Unit I and II part 2

Complete Linux system = Kernel + GNU system utilities and


libraries + other management scripts + installation scripts.

Shell Scripting
What is Shell?
A shell is a special user program that provides an interface for the user to use operating
system services. Shell accepts human-readable commands from users and converts
them into something which the kernel can understand. It is a command language
interpreter that executes commands read from input devices such as keyboards or from
files. The shell gets started when the user logs in or starts the terminal.

Linux Shell
Shell is broadly classified into two categories –
• Command Line Shell
• Graphical shell
Command Line Shell
Shell can be accessed by users using a command line interface. A special program called
Terminal in Linux/macOS, or Command Prompt in Windows OS is provided to type in
the human-readable commands such as “cat”, “ls” etc. and then it is being executed.
The result is then displayed on the terminal to the user. A terminal in Ubuntu 16.4 system
looks like this –

linux command line


In the above screenshot “ls” command with “-l” option is executed. It will list all the
files in the current working directory in a long listing format.
Working with a command line shell is a bit difficult for beginners because it’s hard to
memorize so many commands. It is very powerful; it allows users to store commands
in a file and execute them together. This way any repetitive task can be easily automated.
These files are usually called batch files in Windows and Shell Scripts in Linux/macOS
systems.
Graphical Shells
Graphical shells provide means for manipulating programs based on the graphical user
interface (GUI), by allowing for operations such as opening, closing, moving, and
resizing windows, as well as switching focus between windows. Window OS or Ubuntu
OS can be considered as a good example which provides GUI to the user for interacting
with the program. Users do not need to type in commands for every action. A typical
GUI in the Ubuntu system –
GUI Shell
There are several shells are available for Linux systems like –
• BASH (Bourne Again SHell) – It is the most widely used shell in Linux
systems. It is used as default login shell in Linux systems and in macOS. It can
also be installed on Windows OS.
• CSH (C SHell) – The C shell’s syntax and its usage are very similar to the C
programming language.
• KSH (Korn SHell) – The Korn Shell was also the base for the POSIX Shell
standard specifications etc.
Each shell does the same job but understands different commands and provides different
built-in functions.
What is a terminal?
A program which is responsible for providing an interface to a user so that he/she can
access the shell. It basically allows users to enter commands and see the output of those
commands in a text-based interface. Large scripts that are written to automate and
perform complex tasks are executed in the terminal.

To access the terminal, simply search in search box “terminal” and double-click it.
Shell Scripting
Usually, shells are interactive, which means they accept commands as input from users
and execute them. However, sometimes we want to execute a bunch of commands
routinely, so we have to type in all commands each time in the terminal.
As a shell can also take commands as input from file, we can write these commands in
a file and can execute them in shell to avoid this repetitive work. These files are
called Shell Scripts or Shell Programs. Shell scripts are similar to the batch file in MS-
DOS. Each shell script is saved with `.sh` file extension e.g., myscript.sh.
A shell script has syntax just like any other programming language. If you have any
prior experience with any programming language like Python, C/C++ etc. It would be
very easy to get started with it.
A shell script comprises the following elements –
• Shell Keywords – if, else, break etc.
• Shell commands – cd, ls, echo, pwd, touch etc.
• Functions
• Control flow – if..then..else, case and shell loops etc.
Why do we need shell scripts?
There are many reasons to write shell scripts:
• To avoid repetitive work and automation
• System admins use shell scripting for routine backups.
• System monitoring
• Adding new functionality to the shell etc.
Advantages of shell scripts
• The command and syntax are exactly the same as those directly entered in the
command line, so programmers do not need to switch to entirely different syntax
• Writing shell scripts are much quicker
• Quick start
• Interactive debugging etc.
Disadvantages of shell scripts
• Prone to costly errors, a single mistake can change the command which might
be harmful.
• Slow execution speed
• Design flaws within the language syntax or implementation
• Not well suited for large and complex task
• Provide minimal data structure unlike other scripting languages. etc.

Process Management in OS
A Program does nothing unless its instructions are executed by a CPU. A program in
execution is called a process. In order to accomplish its task, process needs the computer
resources.
There may exist more than one process in the system which may require the same
resource at the same time. Therefore, the operating system has to manage all the
processes and the resources in a convenient and efficient way.
Some resources may need to be executed by one process at one time to maintain the
consistency otherwise the system can become inconsistent and deadlock may occur.
The operating system is responsible for the following activities in connection with
Process Management
1. Scheduling processes and threads on the CPUs.
2. Creating and deleting both user and system processes.
3. Suspending and resuming processes.
4. Providing mechanisms for process synchronization.
5. Providing mechanisms for process communication.
Process State Diagram

The process, from its creation to completion, passes through various states. The
minimum number of states is five.
The names of the states are not standardized although the process may be in one of the
following states during execution.
1. New
A program which is going to be picked up by the OS into the main memory is called a
new process.
2. Ready
Whenever a process is created, it directly enters in the ready state, in which, it waits for
the CPU to be assigned. The OS picks the new processes from the secondary memory
and put all of them in the main memory.
The processes which are ready for the execution and reside in the main memory are
called ready state processes. There can be many processes present in the ready state.
3. Running
One of the processes from the ready state will be chosen by the OS depending upon the
scheduling algorithm. Hence, if we have only one CPU in our system, the number of
running processes for a particular time will always be one. If we have n processors in
the system then we can have n processes running simultaneously.
4. Block or wait
From the Running state, a process can make the transition to the block or wait state
depending upon the scheduling algorithm or the intrinsic behavior of the process.
When a process waits for a certain resource to be assigned or for the input from the user
then the OS move this process to the block or wait state and assigns the CPU to the
other processes.
5. Completion or termination
When a process finishes its execution, it comes in the termination state. All the context
of the process (Process Control Block) will also be deleted the process will be
terminated by the Operating system.

System Calls in Operating System (OS)


A system call is a way for a user program to interface with the operating system. The
program requests several services, and the OS responds by invoking a series of system
calls to satisfy the request. A system call can be written in assembly language or a high-
level language like C or Pascal. System calls are predefined functions that the operating
system may directly invoke if a high-level language is used.
In this article, you will learn about the system calls in the operating system and discuss
their types and many other things.
What is a System Call?
A system call is a method for a computer program to request a service from the kernel
of the operating system on which it is running. A system call is a method of interacting
with the operating system via programs. A system call is a request from computer
software to an operating system's kernel.
The Application Program Interface (API) connects the operating system's functions
to user programs. It acts as a link between the operating system and a process, allowing
user-level programs to request operating system services. The kernel system can only
be accessed using system calls. System calls are required for any programs that use
resources.
How are system calls made?
When a computer software needs to access the operating system's kernel, it makes a
system call. The system call uses an API to expose the operating system's services to
user programs. It is the only method to access the kernel system. All programs or
processes that require resources for execution must use system calls, as they serve as an
interface between the operating system and user programs.
Below are some examples of how a system call varies from a user function.
1. A system call function may create and use kernel processes to execute the
asynchronous processing.
2. A system call has greater authority than a standard subroutine. A system call with
kernel-mode privilege executes in the kernel protection domain.
3. System calls are not permitted to use shared libraries or any symbols that are not
present in the kernel protection domain.
4. The code and data for system calls are stored in global kernel memory.
Why do you need system calls in Operating System?
There are various situations where you must require system calls in the operating
system. Following of the situations are as follows:
1. It is must require when a file system wants to create or delete a file.
2. Network connections require the system calls to sending and receiving data
packets.
3. If you want to read or write a file, you need to system calls.
4. If you want to access hardware devices, including a printer, scanner, you need a
system call.
5. System calls are used to create and manage new processes.
How System Calls Work?
The Applications run in an area of memory known as user space. A system call connects
to the operating system's kernel, which executes in kernel space. When an application
creates a system call, it must first obtain permission from the kernel. It achieves this
using an interrupt request, which pauses the current process and transfers control to the
kernel.
If the request is permitted, the kernel performs the requested action, like creating or
deleting a file. As input, the application receives the kernel's output. The application
resumes the procedure after the input is received. When the operation is finished, the
kernel returns the results to the application and then moves data from kernel space to
user space in memory.
A simple system call may take few nanoseconds to provide the result, like retrieving the
system date and time. A more complicated system call, such as connecting to a network
device, may take a few seconds. Most operating systems launch a distinct kernel thread
for each system call to avoid bottlenecks. Modern operating systems are multi-threaded,
which means they can handle various system calls at the same time.
Types of System Calls
There are commonly five types of system calls. These are as follows:

1. Process Control
2. File Management
3. Device Management
4. Information Maintenance
5. Communication
Now, you will learn about all the different types of system calls one-by-one.
Process Control
Process control is the system call that is used to direct the processes. Some process
control examples include creating, load, abort, end, execute, process, terminate the
process, etc.
File Management
File management is a system call that is used to handle the files. Some file management
examples include creating files, delete files, open, close, read, write, etc.
Device Management
Device management is a system call that is used to deal with devices. Some examples
of device management include read, device, write, get device attributes, release device,
etc.
Information Maintenance
Information maintenance is a system call that is used to maintain information. There are
some examples of information maintenance, including getting system data, set time or
date, get time or date, set system data, etc.
Communication
Communication is a system call that is used for communication. There are some
examples of communication, including create, delete communication connections, send,
receive messages, etc.
Examples of Windows and Unix system calls
There are various examples of Windows and Unix system calls. These are as listed
below in the table:
Process Windows Unix
Process Control CreateProcess() Fork()
ExitProcess() Exit()
WaitForSingleObject() Wait()
File Manipulation CreateFile() Open()
ReadFile() Read()
WriteFile() Write()
CloseHandle() Close()
Device Management SetConsoleMode() Ioctl()
ReadConsole() Read()
WriteConsole() Write()
Information Maintenance GetCurrentProcessID() Getpid()
SetTimer() Alarm()
Sleep() Sleep()
Communication CreatePipe() Pipe()
CreateFileMapping() Shmget()
MapViewOfFile() Mmap()
Protection SetFileSecurity() Chmod()
InitializeSecurityDescriptor() Umask()
SetSecurityDescriptorgroup() Chown()
Here, you will learn about some methods briefly:
open()
The open() system call allows you to access a file on a file system. It allocates resources
to the file and provides a handle that the process may refer to. Many processes can open
a file at once or by a single process only. It's all based on the file system and structure.
ADVERTISEMENT
read()
It is used to obtain data from a file on the file system. It accepts three arguments in
general:
o A file descriptor.
o A buffer to store read data.
o The number of bytes to read from the file.

The file descriptor of the file to be read could be used to identify it and open it
using open() before reading.
wait()
In some systems, a process may have to wait for another process to complete its
execution before proceeding. When a parent process makes a child process, the parent
process execution is suspended until the child process is finished. The wait() system
call is used to suspend the parent process. Once the child process has completed its
execution, control is returned to the parent process.
write()
It is used to write data from a user buffer to a device like a file. This system call is one
way for a program to generate data. It takes three arguments in general:
o A file descriptor.
o A pointer to the buffer in which data is saved.
o The number of bytes to be written from the buffer.
fork()
Processes generate clones of themselves using the fork() system call. It is one of the
most common ways to create processes in operating systems. When a parent process
spawns a child process, execution of the parent process is interrupted until the child
process completes. Once the child process has completed its execution, control is
returned to the parent process.
close()
It is used to end file system access. When this system call is invoked, it signifies that
the program no longer requires the file, and the buffers are flushed, the file information
is altered, and the file resources are de-allocated as a result.
exec()
When an executable file replaces an earlier executable file in an already executing
process, this system function is invoked. As a new process is not built, the old process
identification stays, but the new process replaces data, stack, data, head, etc.
exit()
The exit() is a system call that is used to end program execution. This call indicates that
the thread execution is complete, which is especially useful in multi-threaded
environments. The operating system reclaims resources spent by the process following
the use of the exit() system function.
System calls are the calls that a program makes to the system kernel to provide the
services to which the program does not have direct access. For example, providing
access to input and output devices such as monitors and keyboards. We can use various
functions provided in the C Programming language for input/output system calls such
as create, open, read, write, etc. Before we move on to the I/O System Calls, we need
to know about a few important terms.
Important Terminology
What is the File Descriptor?
The file descriptor is an integer that uniquely identifies an open file of the process.
File Descriptor table: A file descriptor table is the collection of integer array indices
that are file descriptors in which elements are pointers to file table entries. One unique
file descriptors table is provided in the operating system for each process.
File Table Entry: File table entries are a structure In-memory surrogate for an open
file, which is created when processing a request to open the file and these entries
maintain file position.

Standard File Descriptors: When any process starts, then that process file descriptors
table’s fd(file descriptor) 0, 1, 2 open automatically, (By default) each of these 3 fd
references file table entry for a file named /dev/tty
/dev/tty: In-memory surrogate for the terminal.
Terminal: Combination keyboard/video screen.

Read from stdin => read from fd 0: Whenever we write any character from the
keyboard, it reads from stdin through fd 0 and saves to a file named /dev/tty.
Write to stdout => write to fd 1: Whenever we see any output to the video screen, it’s
from the file named /dev/tty and written to stdout in screen through fd 1.
Write to stderr => write to fd 2: We see any error to the video screen, it is also from
that file write to stderr in screen through fd 2.
Header file Information
• fcntl.h
The fcntl.h header file in C contains declarations for file control operations. This
includes opening, closing, reading, writing, and locking files. It also includes functions
for getting and setting file attributes, such as the file size, permissions, and access time.
The fcntl.h header file is used by the fcntl() function, which is used to perform various
operations on files. The fcntl() function takes two arguments: the file descriptor of the
file to be operated on, and a command that specifies the operation to be performed.
Here are some of the commands that can be used with the fcntl() function:
• F_DUPFD: Duplicates the file descriptor.
• F_GETFD: Gets the file descriptor flags.
• F_SETFD: Sets the file descriptor flags.
• F_GETFL: Gets the file status flags.
• F_SETFL: Sets the file status flags.
• F_GETLK: Gets record locking information.
• F_SETLK: Sets record locking information.
• F_SETLKW: Sets record locking information and waits for the lock to be
granted.
The fcntl.h header file is a powerful tool for controlling file operations in C. It can be
used to perform a wide variety of tasks, such as opening files, reading and writing files,
locking files, and getting and setting file attributes.

• stdio.h
The stdio.h header file is a standard library header file in C programming. It contains
functions, macros, and variables for performing input and output operations.
The stdio.h header file is one of the most important header files in C programming. It
is used in almost every C program.
Some of the important functions defined in the stdio.h header file are:
• printf(): This function is used to print formatted output to the console.
• scanf(): This function is used to read formatted input from the console.
• fopen(): This function is used to open a file.
• fclose(): This function is used to close a file.
• fgetc(): This function is used to read a single character from a file.
• fputc(): This function is used to write a single character to a file.
• fgets(): This function is used to read a line of text from a file.
• fputs(): This function is used to write a line of text to a file.
The stdio.h header file also defines a number of macros, such as:
• EOF: This macro represents the end of a file.
• NULL: This macro represents a null pointer.
The stdio.h header file is a powerful tool for performing input and output operations in
C programming. It is essential for writing any C program that needs to interact with the
user or with files.

• unistd.h
The unistd.h header file in C is a system header file that provides access to the operating
system API. It is defined by the POSIX.1 standard, the base of the Single Unix
Specification, and should therefore be available in any POSIX-compliant operating
system and compiler.
The name unistd.h is likely a combination of "Unix" (uni) and "standard" (std), resulting
in a "Unix standard header". However, the six-character name might be related to
various DEC file system limitations.
The unistd.h header file defines a number of symbolic constants and types, and declares
a number of functions. The symbolic constants are used to specify various options and
flags to the functions. The types are used to represent various data structures, such as
file descriptors and process IDs. The functions provide access to a variety of operating
system services, such as file I/O, process management, and inter-process
communication.
Here are some of the functions declared in unistd.h:
• access(): - Checks whether a file exists and whether the user has permission to
access it.
• chdir(): - Changes the current working directory.
• close(): - Closes a file descriptor.
• creat(): - Creates a new file.
• dup(): - Duplicates a file descriptor.
• execve(): - Executes a new program.
• fork(): - Creates a new process.
• getpid(): - Gets the process ID of the current process.
• lseek(): - Changes the position of the file pointer in a file.
• open(): - Opens a file.
• read(): - Reads data from a file.
• stat(): - Gets information about a file.
• unlink(): - Deletes a file.
• write(): - Writes data to a file.
The unistd.h header file is a powerful tool that provides access to a wide variety of
operating system services. It is an essential header file for any C program that needs to
interact with the operating system.

• stdin.h
The stdio.h header file in C contains declarations for functions that perform input and
output operations. This includes the stdin stream, which is the standard input
stream. The stdin stream is typically connected to the keyboard, but it can also be
connected to other sources, such as a file.
The getchar() function reads a single character from
the stdin stream. The fgets() function reads a line of text from the stdin stream, up to
and including the newline character.

File Descriptor
All system calls for performing I/O refer to open files using a file descriptor, a (usually
small) nonnegative integer. There are 3 standard file descriptor by default available in
Linux.
File Descriptor Description POSIX name Stdio stream
0 Standard input STDIN_FILENO stdin
1 Standard output STDOUT_FILENO stdout

2 Standard error STDERR_FILENO stderr

All file related operations are performed via file descriptor(fd)


Input/Output System Calls
Basically, there are total 5 types of I/O system calls:
1. C create
The create() function is used to create a new empty file in C. We can specify the
permission and the name of the file which we want to create using the create() function.
It is defined inside <unistd.h> header file and the flags that are passed as arguments are
defined inside <fcntl.h> header file.
Syntax of create() in C
int create(char *filename, mode_t mode);

Parameter
• filename: name of the file which you want to create
• mode: indicates permissions of the new file.
Return Value
• return first unused file descriptor (generally 3 when first creating use in the
process because 0, 1, 2 fd are reserved)
• return -1 when an error
How C create() works in OS
• Create a new empty file on the disk.
• Create file table entry.
• Set the first unused file descriptor to point to the file table entry.
• Return file descriptor used, -1 upon failure.
2. C open
The open() function in C is used to open the file for reading, writing, or both. It is also
capable of creating the file if it does not exist. It is defined inside <unistd.h> header
file and the flags that are passed as arguments are defined inside <fcntl.h> header file.
Syntax of open() in C
int open (const char* Path, int flags);
Parameters
• Path: Path to the file which we want to open.
• Use the absolute path beginning with “/” when you are not working in
the same directory as the C source file.
• Use relative path which is only the file name with extension, when you
are working in the same directory as the C source file.
• flags: It is used to specify how you want to open the file. We can use the
following flags.
Flags Description
O_RDONLY Opens the file in read-only mode.
O_WRONLY Opens the file in write-only mode.
O_RDWR Opens the file in read and write mode.
O_CREAT Create a file if it doesn’t exist.
O_EXCL Prevent creation if it already exists.
O_ APPEND Opens the file and places the cursor at the end of the contents.
O_ASYNC Enable input and output control by signal.
O_CLOEXEC Enable close-on-exec mode on the open file.
O_NONBLOCK Disables blocking of the file opened.
O_TMPFILE Create an unnamed temporary file at the specified path.
How C open() works in OS
• Find the existing file on the disk.
• Create file table entry.
• Set the first unused file descriptor to point to the file table entry.
• Return file descriptor used, -1 upon failure.

Example of C open()
sandeshyewale@Sandeshs-MBP aarti % vi startup1.txt
sandeshyewale@Sandeshs-MBP aarti % vi open_1.c
//open_1.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>

void main(){
int fd;
fd = open("startup1.txt", O_RDONLY);
if (fd == -1){
printf("\n open() was failed - errno = (%d)\n",errno);
perror("ERROR:");
}
else
{
printf("\n open() system call executed successfully\n");
}

sandeshyewale@Sandeshs-MBP aarti % cat startup1.txt


This is startup file
sandeshyewale@Sandeshs-MBP aarti % gcc open_1.c -o open_1
sandeshyewale@Sandeshs-MBP aarti % ./open_1
Output
open() system call executed successfully
sandeshyewale@Sandeshs-MBP aarti %

In order to perform any operation like reading/writing a file, we need to open the file
and provide a handle to the kernel. Any further operations on this file, will be done using
this handle.

Ref: https://www.udemy.com/course/linux-system-programming-f/learn/lecture/20870898#overview
3. C close
The close() function in C tells the operating system that you are done with a file
descriptor and closes the file pointed by the file descriptor. It is defined
inside <unistd.h> header file.
Syntax of close() in C
int close(int fd);
Parameter
• fd: File descriptor of the file that you want to close.
Return Value
• 0 on success.
• -1 on error.
How C close() works in the OS
• Destroy file table entry referenced by element fd of the file descriptor table
– As long as no other process is pointing to it!
• Set element fd of file descriptor table to NULL

Example 1: close() in C
// C program to illustrate close system Call
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

int main()
{
int fd1 = open("startup1.txt", O_RDONLY);
if (fd1 < 0) {
perror("c1");
exit(1);
}
printf("opened the fd = % d\n", fd1);
// Using close system Call
if (close(fd1) < 0) {
perror("c1");
exit(1);
}
printf("closed the fd.\n");
}
Output
opened the fd = 3
closed the fd.

Examples to be covered from aarti folder


Open_1.c
Open_2.c
Open_3.c
Read.c
Write1.c
Write2.c
Write3.c

Example 2:
// C program to illustrate close system Call
#include<stdio.h>
#include<fcntl.h>
int main()
{
// assume that foo.txt is already created
int fd1 = open("foo.txt", O_RDONLY, 0);
close(fd1);
// assume that baz.tzt is already created
int fd2 = open("baz.txt", O_RDONLY, 0);

printf("fd2 = % d\n", fd2);


exit(0);
}
Output
fd2 = 3
Here, In this code first open() returns 3 because when the main process is created, then
fd 0, 1, 2 are already taken by stdin, stdout, and stderr. So the first unused file
descriptor is 3 in the file descriptor table. After that in close() system call is free it
these 3 file descriptors and then set 3 file descriptors as null. So when we called the
second open(), then the first unused fd is also 3. So, the output of this program is 3.
4. C read
From the file indicated by the file descriptor fd, the read() function reads the specified
amount of bytes cnt of input into the memory area indicated by buf. A successful read()
updates the access time for the file. The read() function is also defined inside the
<unistd.h> header file.
Syntax of read() in C
size_t read (int fd, void* buf, size_t cnt);
Parameters
• fd: file descriptor of the file from which data is to be read.
• buf: buffer to read data from
• cnt: length of the buffer
Return Value
• return Number of bytes read on success
• return 0 on reaching the end of file
• return -1 on error
• return -1 on signal interrupt
Important Points
• buf needs to point to a valid memory location with a length not smaller than the
specified size because of overflow.
• fd should be a valid file descriptor returned from open() to perform the read
operation because if fd is NULL then the read should generate an error.
• cnt is the requested number of bytes read, while the return value is the actual
number of bytes read. Also, some times read system call should read fewer bytes
than cnt.
Example of read() in C
• C

// C program to illustrate
// read system Call
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

int main()
{
int fd, sz;
char* c = (char*)calloc(100, sizeof(char));

fd = open("foo.txt", O_RDONLY);
if (fd < 0) {
perror("r1");
exit(1);
}
sz = read(fd, c, 10);
printf("called read(% d, c, 10). returned that"
" %d bytes were read.\n",
fd, sz);
c[sz] = '\0';
printf("Those bytes are as follows: % s\n", c);
return 0;
}

Output
called read(3, c, 10). returned that 10 bytes were read.
Those bytes are as follows: 0 0 0 foo.
Suppose that foobar.txt consists of the 6 ASCII characters “foobar”. Then what is
the output of the following program?

// C program to illustrate
// read system Call
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
char c;
int fd1 = open("sample.txt", O_RDONLY, 0);
int fd2 = open("sample.txt", O_RDONLY, 0);
read(fd1, &c, 1);
read(fd2, &c, 1);
printf("c = %c\n", c);
exit(0);
}

Output
c=f
The descriptors fd1 and fd2 each have their own open file table entry, so each descriptor
has its own file position for foobar.txt. Thus, the read from fd2 reads the first byte
of foobar.txt, and the output is c = f, not c = o.
5. C write
Writes cnt bytes from buf to the file or socket associated with fd. cnt should not be
greater than INT_MAX (defined in the limits.h header file). If cnt is zero, write() simply
returns 0 without attempting any other action.
The write() is also defined inside <unistd.h> header file.
Syntax of write() in C
size_t write (int fd, void* buf, size_t cnt);
Parameters
• fd: file descriptor
• buf: buffer to write data from.
• cnt: length of the buffer.
Return Value
• returns the number of bytes written on success.
• return 0 on reaching the End of File.
• return -1 on error.
• return -1 on signal interrupts.
Important Points about C write
• The file needs to be opened for write operations
• buf needs to be at least as long as specified by cnt because if buf size is less than
the cnt then buf will lead to the overflow condition.
• cnt is the requested number of bytes to write, while the return value is the actual
number of bytes written. This happens when fd has a less number of bytes to
write than cnt.
• If write() is interrupted by a signal, the effect is one of the following:
• If write() has not written any data yet, it returns -1 and sets errno to
EINTR.
• If write() has successfully written some data, it returns the number of
bytes it wrote before it was interrupted.
Example of write() in C

// C program to illustrate write system Call


#include<stdio.h>
#include <fcntl.h>
main()
{
int sz;
int fd = open("foo.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd < 0)
{
perror("r1");
exit(1);
}
sz = write(fd, "hello geeks\n", strlen("hello geeks\n"));
printf("called write(% d, \"hello geeks\\n\", %d)."
" It returned %d\n", fd, strlen("hello geeks\n"), sz);
close(fd);
}

Output
called write(3, "hello geeks\n", 12). it returned 11
Here, when you see in the file foo.txt after running the code, you get a “hello geeks”. If
foo.txt file already has some content in it then the write system calls overwrite the
content and all previous content is deleted and only “hello geeks” content will have in
the file.
Example: Print “hello world” from the program without using any printf function.

// C program to illustrate I/O system Calls


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

int main(void)
{
int fd[2];
char buf1[12] = "hello world";
char buf2[12];

// assume foobar.txt is already created


fd[0] = open("foobar.txt", O_RDWR);
fd[1] = open("foobar.txt", O_RDWR);
write(fd[0], buf1, strlen(buf1));
write(1, buf2, read(fd[1], buf2, 12));
close(fd[0]);
close(fd[1]);
return 0;
}

Output
hello world
In this code, buf1 array’s string “hello world” is first written into stdin fd[0] then after
that this string write into stdin to buf2 array. After that write into buf2 array to the stdout
and print output hello world.

References:
1. https://www.javatpoint.com/system-calls-in-operating-system
2. https://www.geeksforgeeks.org/input-output-system-calls-c-create-open-close-
read-write/
3. https://www.skillvertex.com/blog/input-output-system-calls-in-c-create-open-
close-read-write/
4. https://www.quora.com/What-are-the-differences-between-the-open-close-
read-and-write-system-calls-in-the-Linux-operating-system
5. https://www.javatpoint.com/system-calls-in-operating-system
6. https://pubs.opengroup.org/onlinepubs/007904975/basedefs/fcntl.h.html
7. https://man7.org/linux/man-pages/man0/fcntl.h.0p.html
8.

You might also like