The document discusses UNIX file APIs. It describes how UNIX applications interface with files by creating, opening, reading, writing, closing, removing, and querying files. It covers APIs like open(), read(), write(), close(), unlink(), stat(), and others. It also describes different file types in UNIX like regular files, directories, FIFOs, devices, and symbolic links. The APIs to manage these different file types are also covered.
Contents:-
Introduction
What is a File?
High Level I/O Functions
Defining & Opening a File
Closing a File
The getc and putc Functions
The getw and putw Functions
The fprintf and fscanf Functions
Text Input / Output: Files, Streams, Standard Library Input / Output Functions, Formatting Input / Output Functions, Character Input / Output Functions, Binary Input / Output: Text versus Binary Streams, Standard Library, Functions for Files, Converting File Type
Wherever there is a need to handle large volumes of data, it is advantageous to store data on the disks and read whenever necessary. This method employs the concept of files to store data. A file is a place on disk where a group of related data is stored.file handling c programming tutorial
introduction, file, types of files, need for file handling, steps for processing a file, file input/out functions {declaraion of file, opening a file, reading data from a file, writing data in a file, closing the file}, programs #technology #computers
Unix , Linux Commands
Unix, which is not an acronym, was developed by some of the members of the Multics team at the bell labs starting in the late 1960's by many of the same people who helped create the C programming language.
An operating system (OS) is system software that manages computer hardware, software resources, and provides common services for computer programs.
Time-sharing operating systems schedule tasks for efficient use of the system and may also include accounting software for cost allocation of processor time, mass storage, printing, and other resources.
For hardware functions such as input and output and memory allocation, the operating system acts as an intermediary between programs and the computer hardware,[1][2] although the application code is usually executed directly by the hardware and frequently makes system calls to an OS function or is interrupted by it. Operating systems are found on many devices that contain a computer – from cellular phones and video game consoles to web servers and supercomputers.
The dominant general-purpose[3] personal computer operating system is Microsoft Windows with a market share of around 76.45%. macOS by Apple Inc. is in second place (17.72%), and the varieties of Linux are collectively in third place (1.73%).[4] In the mobile sector (including smartphones and tablets), Android's share is up to 72% in the year 2020.[5] According to third quarter 2016 data, Android's share on smartphones is dominant with 87.5 percent with also a growth rate of 10.3 percent per year, followed by Apple's iOS with 12.1 percent with per year decrease in market share of 5.2 percent, while other operating systems amount to just 0.3 percent.[6] Linux distributions are dominant in the server and supercomputing sectors. Other specialized classes of operating systems (special-purpose operating systems),[3][7] such as embedded and real-time systems, exist for many applications. Security-focused operating systems also exist. Some operating systems have low system requirements (e.g. light-weight Linux distribution). Others may have higher system requirements.
A Comprehensive Look at Generative AI in Retail App Testing.pdfkalichargn70th171
Traditional software testing methods are being challenged in retail, where customer expectations and technological advancements continually shape the landscape. Enter generative AI—a transformative subset of artificial intelligence technologies poised to revolutionize software testing.
Contents:-
Introduction
What is a File?
High Level I/O Functions
Defining & Opening a File
Closing a File
The getc and putc Functions
The getw and putw Functions
The fprintf and fscanf Functions
Text Input / Output: Files, Streams, Standard Library Input / Output Functions, Formatting Input / Output Functions, Character Input / Output Functions, Binary Input / Output: Text versus Binary Streams, Standard Library, Functions for Files, Converting File Type
Wherever there is a need to handle large volumes of data, it is advantageous to store data on the disks and read whenever necessary. This method employs the concept of files to store data. A file is a place on disk where a group of related data is stored.file handling c programming tutorial
introduction, file, types of files, need for file handling, steps for processing a file, file input/out functions {declaraion of file, opening a file, reading data from a file, writing data in a file, closing the file}, programs #technology #computers
Unix , Linux Commands
Unix, which is not an acronym, was developed by some of the members of the Multics team at the bell labs starting in the late 1960's by many of the same people who helped create the C programming language.
An operating system (OS) is system software that manages computer hardware, software resources, and provides common services for computer programs.
Time-sharing operating systems schedule tasks for efficient use of the system and may also include accounting software for cost allocation of processor time, mass storage, printing, and other resources.
For hardware functions such as input and output and memory allocation, the operating system acts as an intermediary between programs and the computer hardware,[1][2] although the application code is usually executed directly by the hardware and frequently makes system calls to an OS function or is interrupted by it. Operating systems are found on many devices that contain a computer – from cellular phones and video game consoles to web servers and supercomputers.
The dominant general-purpose[3] personal computer operating system is Microsoft Windows with a market share of around 76.45%. macOS by Apple Inc. is in second place (17.72%), and the varieties of Linux are collectively in third place (1.73%).[4] In the mobile sector (including smartphones and tablets), Android's share is up to 72% in the year 2020.[5] According to third quarter 2016 data, Android's share on smartphones is dominant with 87.5 percent with also a growth rate of 10.3 percent per year, followed by Apple's iOS with 12.1 percent with per year decrease in market share of 5.2 percent, while other operating systems amount to just 0.3 percent.[6] Linux distributions are dominant in the server and supercomputing sectors. Other specialized classes of operating systems (special-purpose operating systems),[3][7] such as embedded and real-time systems, exist for many applications. Security-focused operating systems also exist. Some operating systems have low system requirements (e.g. light-weight Linux distribution). Others may have higher system requirements.
A Comprehensive Look at Generative AI in Retail App Testing.pdfkalichargn70th171
Traditional software testing methods are being challenged in retail, where customer expectations and technological advancements continually shape the landscape. Enter generative AI—a transformative subset of artificial intelligence technologies poised to revolutionize software testing.
Into the Box Keynote Day 2: Unveiling amazing updates and announcements for modern CFML developers! Get ready for exciting releases and updates on Ortus tools and products. Stay tuned for cutting-edge innovations designed to boost your productivity.
Your Digital Assistant.
Making complex approach simple. Straightforward process saves time. No more waiting to connect with people that matter to you. Safety first is not a cliché - Securely protect information in cloud storage to prevent any third party from accessing data.
Would you rather make your visitors feel burdened by making them wait? Or choose VizMan for a stress-free experience? VizMan is an automated visitor management system that works for any industries not limited to factories, societies, government institutes, and warehouses. A new age contactless way of logging information of visitors, employees, packages, and vehicles. VizMan is a digital logbook so it deters unnecessary use of paper or space since there is no requirement of bundles of registers that is left to collect dust in a corner of a room. Visitor’s essential details, helps in scheduling meetings for visitors and employees, and assists in supervising the attendance of the employees. With VizMan, visitors don’t need to wait for hours in long queues. VizMan handles visitors with the value they deserve because we know time is important to you.
Feasible Features
One Subscription, Four Modules – Admin, Employee, Receptionist, and Gatekeeper ensures confidentiality and prevents data from being manipulated
User Friendly – can be easily used on Android, iOS, and Web Interface
Multiple Accessibility – Log in through any device from any place at any time
One app for all industries – a Visitor Management System that works for any organisation.
Stress-free Sign-up
Visitor is registered and checked-in by the Receptionist
Host gets a notification, where they opt to Approve the meeting
Host notifies the Receptionist of the end of the meeting
Visitor is checked-out by the Receptionist
Host enters notes and remarks of the meeting
Customizable Components
Scheduling Meetings – Host can invite visitors for meetings and also approve, reject and reschedule meetings
Single/Bulk invites – Invitations can be sent individually to a visitor or collectively to many visitors
VIP Visitors – Additional security of data for VIP visitors to avoid misuse of information
Courier Management – Keeps a check on deliveries like commodities being delivered in and out of establishments
Alerts & Notifications – Get notified on SMS, email, and application
Parking Management – Manage availability of parking space
Individual log-in – Every user has their own log-in id
Visitor/Meeting Analytics – Evaluate notes and remarks of the meeting stored in the system
Visitor Management System is a secure and user friendly database manager that records, filters, tracks the visitors to your organization.
"Secure Your Premises with VizMan (VMS) – Get It Now"
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
How to Position Your Globus Data Portal for Success Ten Good PracticesGlobus
Science gateways allow science and engineering communities to access shared data, software, computing services, and instruments. Science gateways have gained a lot of traction in the last twenty years, as evidenced by projects such as the Science Gateways Community Institute (SGCI) and the Center of Excellence on Science Gateways (SGX3) in the US, The Australian Research Data Commons (ARDC) and its platforms in Australia, and the projects around Virtual Research Environments in Europe. A few mature frameworks have evolved with their different strengths and foci and have been taken up by a larger community such as the Globus Data Portal, Hubzero, Tapis, and Galaxy. However, even when gateways are built on successful frameworks, they continue to face the challenges of ongoing maintenance costs and how to meet the ever-expanding needs of the community they serve with enhanced features. It is not uncommon that gateways with compelling use cases are nonetheless unable to get past the prototype phase and become a full production service, or if they do, they don't survive more than a couple of years. While there is no guaranteed pathway to success, it seems likely that for any gateway there is a need for a strong community and/or solid funding streams to create and sustain its success. With over twenty years of examples to draw from, this presentation goes into detail for ten factors common to successful and enduring gateways that effectively serve as best practices for any new or developing gateway.
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
Les Buildpacks existent depuis plus de 10 ans ! D’abord, ils étaient utilisés pour détecter et construire une application avant de la déployer sur certains PaaS. Ensuite, nous avons pu créer des images Docker (OCI) avec leur dernière génération, les Cloud Native Buildpacks (CNCF en incubation). Sont-ils une bonne alternative au Dockerfile ? Que sont les buildpacks Paketo ? Quelles communautés les soutiennent et comment ?
Venez le découvrir lors de cette session ignite
Software Engineering, Software Consulting, Tech Lead.
Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Security,
Spring Transaction, Spring MVC,
Log4j, REST/SOAP WEB-SERVICES.
Advanced Flow Concepts Every Developer Should KnowPeter Caitens
Tim Combridge from Sensible Giraffe and Salesforce Ben presents some important tips that all developers should know when dealing with Flows in Salesforce.
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Globus
The U.S. Geological Survey (USGS) has made substantial investments in meeting evolving scientific, technical, and policy driven demands on storing, managing, and delivering data. As these demands continue to grow in complexity and scale, the USGS must continue to explore innovative solutions to improve its management, curation, sharing, delivering, and preservation approaches for large-scale research data. Supporting these needs, the USGS has partnered with the University of Chicago-Globus to research and develop advanced repository components and workflows leveraging its current investment in Globus. The primary outcome of this partnership includes the development of a prototype enterprise repository, driven by USGS Data Release requirements, through exploration and implementation of the entire suite of the Globus platform offerings, including Globus Flow, Globus Auth, Globus Transfer, and Globus Search. This presentation will provide insights into this research partnership, introduce the unique requirements and challenges being addressed and provide relevant project progress.
We describe the deployment and use of Globus Compute for remote computation. This content is aimed at researchers who wish to compute on remote resources using a unified programming interface, as well as system administrators who will deploy and operate Globus Compute services on their research computing infrastructure.
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns
Unlocking Business Potential: Tailored Technology Solutions by Prosigns
Discover how Prosigns, a leading technology solutions provider, partners with businesses to drive innovation and success. Our presentation showcases our comprehensive range of services, including custom software development, web and mobile app development, AI & ML solutions, blockchain integration, DevOps services, and Microsoft Dynamics 365 support.
Custom Software Development: Prosigns specializes in creating bespoke software solutions that cater to your unique business needs. Our team of experts works closely with you to understand your requirements and deliver tailor-made software that enhances efficiency and drives growth.
Web and Mobile App Development: From responsive websites to intuitive mobile applications, Prosigns develops cutting-edge solutions that engage users and deliver seamless experiences across devices.
AI & ML Solutions: Harnessing the power of Artificial Intelligence and Machine Learning, Prosigns provides smart solutions that automate processes, provide valuable insights, and drive informed decision-making.
Blockchain Integration: Prosigns offers comprehensive blockchain solutions, including development, integration, and consulting services, enabling businesses to leverage blockchain technology for enhanced security, transparency, and efficiency.
DevOps Services: Prosigns' DevOps services streamline development and operations processes, ensuring faster and more reliable software delivery through automation and continuous integration.
Microsoft Dynamics 365 Support: Prosigns provides comprehensive support and maintenance services for Microsoft Dynamics 365, ensuring your system is always up-to-date, secure, and running smoothly.
Learn how our collaborative approach and dedication to excellence help businesses achieve their goals and stay ahead in today's digital landscape. From concept to deployment, Prosigns is your trusted partner for transforming ideas into reality and unlocking the full potential of your business.
Join us on a journey of innovation and growth. Let's partner for success with Prosigns.
Why React Native as a Strategic Advantage for Startup Innovation.pdfayushiqss
Do you know that React Native is being increasingly adopted by startups as well as big companies in the mobile app development industry? Big names like Facebook, Instagram, and Pinterest have already integrated this robust open-source framework.
In fact, according to a report by Statista, the number of React Native developers has been steadily increasing over the years, reaching an estimated 1.9 million by the end of 2024. This means that the demand for this framework in the job market has been growing making it a valuable skill.
But what makes React Native so popular for mobile application development? It offers excellent cross-platform capabilities among other benefits. This way, with React Native, developers can write code once and run it on both iOS and Android devices thus saving time and resources leading to shorter development cycles hence faster time-to-market for your app.
Let’s take the example of a startup, which wanted to release their app on both iOS and Android at once. Through the use of React Native they managed to create an app and bring it into the market within a very short period. This helped them gain an advantage over their competitors because they had access to a large user base who were able to generate revenue quickly for them.
In software engineering, the right architecture is essential for robust, scalable platforms. Wix has undergone a pivotal shift from event sourcing to a CRUD-based model for its microservices. This talk will chart the course of this pivotal journey.
Event sourcing, which records state changes as immutable events, provided robust auditing and "time travel" debugging for Wix Stores' microservices. Despite its benefits, the complexity it introduced in state management slowed development. Wix responded by adopting a simpler, unified CRUD model. This talk will explore the challenges of event sourcing and the advantages of Wix's new "CRUD on steroids" approach, which streamlines API integration and domain event management while preserving data integrity and system resilience.
Participants will gain valuable insights into Wix's strategies for ensuring atomicity in database updates and event production, as well as caching, materialization, and performance optimization techniques within a distributed system.
Join us to discover how Wix has mastered the art of balancing simplicity and extensibility, and learn how the re-adoption of the modest CRUD has turbocharged their development velocity, resilience, and scalability in a high-growth environment.
How Recreation Management Software Can Streamline Your Operations.pptxwottaspaceseo
Recreation management software streamlines operations by automating key tasks such as scheduling, registration, and payment processing, reducing manual workload and errors. It provides centralized management of facilities, classes, and events, ensuring efficient resource allocation and facility usage. The software offers user-friendly online portals for easy access to bookings and program information, enhancing customer experience. Real-time reporting and data analytics deliver insights into attendance and preferences, aiding in strategic decision-making. Additionally, effective communication tools keep participants and staff informed with timely updates. Overall, recreation management software enhances efficiency, improves service delivery, and boosts customer satisfaction.
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
Experience our free, in-depth three-part Tendenci Platform Corporate Membership Management workshop series! In Session 1 on May 14th, 2024, we began with an Introduction and Setup, mastering the configuration of your Corporate Membership Module settings to establish membership types, applications, and more. Then, on May 16th, 2024, in Session 2, we focused on binding individual members to a Corporate Membership and Corporate Reps, teaching you how to add individual members and assign Corporate Representatives to manage dues, renewals, and associated members. Finally, on May 28th, 2024, in Session 3, we covered questions and concerns, addressing any queries or issues you may have.
For more Tendenci AMS events, check out www.tendenci.com/events
2. UNIX FILE APIS
This chapter describes how the UNIX applications interface with files.
- Create files.
- Open files.
- Transfer data to and from files.
- Close files.
- Remove files.
- Query file attributes.
- Change file attributes.
- Truncate files.
3. UNIX FILE
File in UNIX system may be one of the following types.
Regular file.
Directory file.
FIFO file.
Character device file.
Block device file.
Symbolic Link file.
4. FILE API USE
open This API is used by a process to open a file for data access.
read The API is used by a process to read data from a file
write The API is used by a process to write data to a file
lseek The API is used by a process to allow random access to a file
close The API is used by a process to terminate connection to a file
stat The API is used by a process to query file attributes
fstat The API is used by a process to query file attributes
5. chmod The API is used by a process to change file access permissions.
chown The API is used by a process to change UID and GID of a file
utime The API is used by a process to change the last modification
and access time stamps of a file
link The API is used by a process to create a hard link to a file.
unlink The API is used by a process to delete hard link of a file
Umask The API is used by a process to set default file creation mask.
7. open
Access mode flags:
O_RDONLY Open the file for read only.
O_WRONLY Open the file for write only
O_RDWR Open the file for read and write
8. open
Access Modifier Flags:
O_APPEND Appends data to the end of the file.
O_CREAT Create the file if it does not exist.
O_EXCL Used with O_CREAT, if the file exists, the call fails. The test
for existence and the creation if the file does not exists.
O_TRUNC If the file exits, discards the file contents and sets the file size to
zero.
O_NOCTTY Species not to use the named terminal device file as the calling
process control terminal.
O_NONBLOCK Specifies that any subsequent read or write on the file should be
non-blocking.
10. open
Permission:
The permission argument is required only if the O_CREAT flag is set in the access_mode
argument.
For example 0764 specifies 7 is for owner, 6 is for group and 4 is for other.
7 = 111 specifies read, write and execution permission for owner.
6 = 110 specifies read, write permission for group.
4 = 100 specifies read permission for others.
11. open
POSIX.1 defines the permission data type as mode_t and its value is manifested constants which
are aliases to octal integer values
USER: S_IRWXU | S_IRUSR | S_IWUSR | S_IXUSR
GROUP: S_IRWXG | S_IRGRP| S_IWGRP | S_IXGRP
OTHERS: S_IRWXO | S_IROTH| S_IWOTH | S_IXOTH
12. open
For example, 0764 permission value should be specified as:
S_IRWXU|S_IRGRP|S_IWGRP|S_IROTH
15. read
This function fetches a fixed size block of data from a file referenced by a given file
descriptor.
#include <sys/types.h>
#include <unistd.h>
ssize_t read (int fdesc ,void* buf, size_t size);
fdesc: is an integer file descriptor that refers to an opened file.
buf: is the address of a buffer holding any data read.
size: specifies how many bytes of data are to be read from the file.
16. write
The write function puts a fixed size block of data to a file referenced by a file descriptor
#include <sys/types.h>
#include <unistd.h>
ssize_t write (int fdesc ,void* buf, size_t size);
fdesc: is an integer file descriptor that refers to an opened file.
buf: is the address of a buffer which contains data to be written to the file.
size: specifies how many bytes of in the buf arguments.
17. close
The close function disconnects a file from a process.
include <unistd.h>
int close (int fdesc);
18. lseek
The lseek system call can be used to change the file offset to a different value.
It allows a process to perform random access of data on any opened file.
#include <sys/types.h>
#include <unistd.h>
off_t lseek (int fdesc , off_t pos, int whence);
fdesc: is an integer file descriptor that refers to an opened file.
pos: specifies a byte offset to be added to a reference location in deriving the new file offset value.
whence: specifies the reference location.
19. lseek
Whence value Reference location
SEEK_CUR Current file pointer address
SEEK_SET The beginning of a file
SEEK_END The end of a file
20. fcntl
The fcntl() function provides for control over open files.
#include <fcntl.h>
int fcntl (int fdesc ,int cmd, ….);
fdesc: is an integer file descriptor that refers to an opened file.
cmd: specifies which operation to perform on a file referenced by the fdesc argument.
The third argument value, which may be specified after cmd is dependent on the actual cmd value.
21. Cmd value Use
F_GETFL Returns the access control flags of a file descriptor fdesc.
F_SETFL Sets or clears access control flags that are specified in the third
argument to fcntl. The allowed access control flags are O_APPEND
and O_NONBLOCK.
F_GETFD Returns the close-on-exec flag of a file referenced by fdesc.
If a return value is zero, the flag is off, otherwise the return value is
nonzero and the flag is on. The close-on-exec flag of a newly opened
file is off by default.
F_SETFD Sets or clears the close-on-exec flag of a file descriptor fdesc.
The third argument to fcntl is integer value, which is 0 to clear, or 1 to
set the flag.
F_DUPFD Duplicates the file descriptor fdesc with another file descriptor.
The third argument to fcntl is an integer value which specifies that the
duplicated file descriptor must be greater than or equal to that value. The
return value of fcntl, in this case is the duplicated file descriptor.
22. link
The link function creates a new link for an existing file
#include <unistd.h>
int link (const char* cur_link ,const char* new_link)
23. unlink
The link function creates a new link for an existing file
#include <unistd.h>
int unlink (const char* cur_link)
24. Implementing mv command with link and unlink command.
#include<iostream.h>
#include<unistd.h>
#include<string.h>
Int main(int argc, char * agrv[])
{
link(agrv[1],argv[2]);
unlink(argv[1]);
return 0;
}
25. remove
#include <unistd.h>
int remove(const char* pathname)
removes the file or directory specified by the path.
if path specifies a directory then remove(path) is equivalent of rmdir(path)
if path specifies a file then remove(path) is equivalent of unlink(path)
26. rename
#include <unistd.h>
int rename(const char* oldname, const char* newname)
causes the link named oldname to renamed as newname.
If the file newname exists, it will be first removed.
both oldname and newname must be:
be both directories or non-directories, but need to be on the same file system.
but they do not have to be on the same directory path.
27. Stat, fstat, lstat
Get information (attributes) of the file.
#include <sys/types.h>
#include<sys/stat.h>
int stat (const char* path_name, struct stat* statv)
int fstat ( int fdesc, struct stat* statv)
int lstat (const char* path_name, struct stat* statv)
28. Struct stat
struct stat
{
dev_ts t_dev; //file system ID
ino_t st_ino; //File inode number
mode_t st_mode; //contains file type and access flags
nlink_t st_nlink; //hard link count
uid_t st_uid; //file user ID
gid_t st_gid; //file group ID
dev_t st_rdev; //contains major and minor device numbers
off_t st_size; //file size in number of bytes
time_t st_atime; //last access time
time_t st_mtime; //last modification time
time_t st_ctime; //last status change time
};
29. CHANGING USER IDs AND GROUP IDs
#include <unistd.h>
int setuid (uid_t uid);
int setgid (gid_t gid);
Both return: 0 if OK, -1 on error
30. access
The access function checks the existence and/or access permission of user to a named file.
#include <unistd.h>
int access (const char* path_name, int flag);
Bit Flag Use
F_OK Checks whether a named file exists.
R_OK Checks whether a calling process has read permission
W_OK Checks whether a calling process has write permission
X_OK Checks whether a calling process has execute permission
32. chmod,fchmod
The chmod and fcmod functions change file access permissions for owner, group and others and also set-UID,
set-GID and sticky flags.
A process that calls one of these functions should have the effective user ID of either the super user or the
owner of the file.
#include <sys/types.h>
#include <sys/sat.h>
#include <unistd.h>
int chmod (const char* path_name, mode_t flag);
int fchmod (int fdsec, mode_t flag);
33. chown,fchown, lchown
The chown and fchown functions change the user ID and group ID of files.
#include <unistd.h>
#include <sys/types.h>
int chown (const char* path_name, uid_t uid, gid_t gid);
int fchown (int fdesc, uid_t uid, gid_t gid);
int lchown (const char* path_name, uid_t uid, gid_t gid);
34. utime
The utime functions modifies the access and modifications time stamps of a file.
#include <unistd.h>
#include <sys/types.h>
#include<utime.h>
int utime (const char* path_name, struct utimbuf* times);
Struct utimbuf
{
time_t actime;
Time_t modtime
}
35. File and Record Locking
File locking is applicable only for regular files
It allows a process to impose a lock on a file so that other processes cannot modify the file until it is
unlocked by the process.
A process can impose a write lock or a read lock on either a portion of a file or an entire file.
A write lock is also known as an exclusive lock
A read lock is also called a shared lock.
36. Mandatory lock
Mandatory locks are enforced by an operating system kernel.
If a mandatory exclusive lock is set on a file, no process can use the read or write system calls to access
data on the locked region.
If a mandatory shared lock is set on a region of a file, no process can use the write system call to modify
the locked region.
Mandatory locks may cause problems: If a runaway process sets a mandatory exclusive lock on a file and
never unlocks it, no other processes can access the locked region of the file until either the runaway
process is killed or the system is rebooted.
37. Advisory lock
Advisory locks are Not enforced by an operating system kernel at the system call level.
This means that even though lock (read or write) may be set on a file, other processes can still use the
read or write APIs to access the file.
To make use of advisory locks, processes that manipulate the same file must cooperate such that they
follow this procedure for every read or write operation to the file:
Try to set a lock at the region to be accessed. If this fails, a process can either wait for the lock request to become
successful or try to lock the file again later.
After a lock is acquired successfully, read or write the locked region
release the lock must
38. Advisory lock
UNIX System V and POSIX.I use the fcntl API for file locking.
#include<fcntl.h>
int fcntl(int fdesc, int cmd_flag, …);
cmd Flag Use
F_SETLK Sets a file lock. Do not block if this cannot succeed immediately
F_SETLKW Sets a file lock and blocks the calling process until the lock is acquired
F_GETLK Queries as to which process locked a specified region of a file
39. For file locking, the third argument to fcntl is an address of a struct flock-typed variable. This variable specifies a
region of a file where the lock is to be set, unset, or queried.
struct flock
{
short l_type; // what lock to be set or to unlock file
short l_whence; // a reference address for the next field
off_t l_start; //offset from the l_whence reference address
off_t l_len; // how many bytes in the locked region
pid_t l_pid; //PID of a process which has locked the file
};
l_ type value Use
F_RDLCK Sets a a read (shared) lock on a specified region
F_WRLCK Sets a write (exclusive) lock on a specified region
F_UNLCK Unlocks a specified region
l_whence value Use
SEEK_CUR The l_start value is added to the current file pointer address.
SEEK_CUR The !_start value is added to the current file pointer Use address
SEEK_SET The l_start value is added to byte 0 of the file
SEEK_END The l_start value ts'added to the end (current size) of the file
40. Directory file APIs
Directory files in UNIX and POSIX systems are used to help users in organizing their files into some
structure based on the specific use of file.
They are also used by the operating system to convert file path names to their inode numbers.
#include <sys/stat.h>
#include <unistd.h>
int mkdir ( const char* path_name, mode t mode );
UNIX System V.3 uses the mknod API to create directory files.
UNIX System V.4 supports both the mkdir and mknod APIs for creating directory files.
mknod does not contain the "." and ".." links. On the other hand, a directory created by mkdir has
the "." and ".." links created in one atomic operation, and it is ready to be used.
41. rmdir()
#include <unistd.h>
int rmdir (const char* path_name);
The following portable functions are defined for directory file browsing. These functions are defined
in both the <dirent.h> and <sys/dir.h> headers.
DIR* opendir (const char* path_name);
Dirent* readdir (DIR* dir_fdesc);
int closedir (DIR* dir_fdesc);
void rewinddir (DIR* dir_fdesc);
opendir: Opens a directory file for read-only. Returns a file handle DIR* for
future reference of the file.
readdir: Reads a record from a directory file referenced by dir_fdesc and
returns that record information.
closedir: Closes a directory file referenced by dir_fdesc.
rewinddir: Resets the file pointer to the beginning of the directory file referenced
by dir_fdesc.
telldir: Returns the file pointer of a given dir_fdesc.
seekdir: Changes the file pointer of a given dir_fdesc to a specified address.
42. Device file APIs
Device files are used to interface physical devices with application programs.
when a process reads or writes to a device file, the kernel uses the major and minor device numbers
of a file to select a device driver function to carry out the actual data transfer.
#include <sys/stat.h>
#include <unistd.h>
int mknod ( const char* path_name, mode t mode, int device_id );
43. Device file APIs
int mknod ( const char* path_name, mode t mode, int device_id );
pathname specifies the path name of the device file to be created.
the mode specifies the access permission as well as the S_IFCHR or S_IFBLK flag.
device_id contains the major and minor device numbers.
the lowest byte of device id is set to a minor device number and the next byte is set to the
major device number.
Ex: mknod(“SCSI5”, S_IFBLK | S_IRWSU | S_IRWSG | S_IRWSO, 15 | 3)
44. Fifo file
FIFO files are sometimes called named pipes.
Pipes can be used only between related processes when a common ancestor has created the pipe.
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
int mkfifo(const char *path_name, mode_t mode);
Ex:
mkfifo(“FIFO5”, S_IFIFO | S_IRWXU | S_IRGRP | S_ROTH);
45. Symbolic link file
A symbolic link is an indirect pointer to a file, unlike the hard links which pointed directly to the inode of the file.
Symbolic links are developed to get around the limitations of hard links:
Symbolic links can link files across file systems.
Symbolic links can link directory files
Symbolic links always reference the latest version of the files to which they link
There are no file system limitations on a symbolic link and what it points to and anyone can create a symbolic link to a
directory.
Symbolic links are typically used to move a file or an entire directory hierarchy to some other location on a system.
48. Process Termination
There are eight ways for a process to terminate.
Normal termination occurs in five ways:
Return from main
Calling exit
Calling _exit or _Exit
Return of the last thread from its start routine
Calling pthread_exit from the last thread
Abnormal termination occurs in three ways:
Receipt of a signal
Response of the last thread to a cancellation request
Calling abort function
49. Exit functions
_exit and _Exit returns to the kernel immediately
exit which performs certain cleanup processing and then returns to the kernel
#include <stdlib.h>
void exit(int status);
void _Exit(int status);
#include <unistd.h>
void _exit(int status);
exit(0); is the same as return(0); from the main function
50. How a C program is started and the various ways it can terminate
51. Command line arguments
#include<unistd.h>
int main(int argc, char *argv[])
{
int i;
for (i = 0; i < argc; i++) /* echo all command-line args */
printf("argv[%d]: %sn", i, argv[i]);
exit(0);
}
Output: $ ./echoarg arg1 TEST foo
argv[0]: ./echoarg
argv[1]: arg1
argv[2]: TEST
argv[3]: foo
52. Environment list
Each program is also passed an environment list along with argument list.
The environment list is an array of character pointers, with each pointer containing the address of a
null-terminated C string.
The address of the array of pointers is contained in the global variable environ:
extern char **environ;
Environment consisting of five C character strings
Generally any environmental variable is of the form: name=value
55. Memory allocation
ISO C specifies three functions for memory allocation:
malloc: Which allocates a specified number of bytes of memory. The initial value of the
memory is indeterminate.
calloc: Which allocates space for a specified number of objects of a specified size. The space is
initialized to all 0 bits.
realloc: Which increases or decreases the size of a previously allocated area.
#include <stdlib.h>
void* malloc(size_t size);
void* calloc(size_t nobj, size_t size);
void* realloc(void *ptr, size_t newsize);
void free(void *ptr);
56. Environment Variables
The environment strings are usually of the form: name=value.
The shells, for example, use numerous environment variables. Some, such as HOME and USER,
which are set automatically at login.
The functions that we can use to set and fetch values from the variables are setenv, putenv,
and getenv functions.
#include <stdlib.h>
char* getenv(const char *name);
Returns: pointer to value associated with name, NULL if not found.
57. Environment Variables
We may want to change the value of an existing variable or add a new variable to the
environment.
#include <stdlib.h>
int putenv(char *str);
int setenv(const char *name, const char *value, int rewrite);
int unsetenv(const char *name);
All return: 0 if OK, nonzero on error
58. Setjmp() and longjmp()
In C, we can't goto a label that's in another function.
we must use the setjmp and longjmp functions to perform this type of branching
these two functions are useful for handling error conditions that occur in a deeply nested
function call.
include <setjmp.h>
int setjmp(jmp_buf env);
Returns: 0 if called directly, nonzero if returning from a call to longjmp
void longjmp(jmp_buf env, int val);
59. #include<stdio.h>
#include<setjmp.h>
jmp_buf env;
void func()
{
printf(“Hello World n");
// Jump to the point setup by setjmp
longjmp(env, 1);
printf(“Good morningn");
}
int main()
{
// Setup jump position using buf and return 0
if (setjmp(env))
{
printf(“Error: cannot proceedn");
exit(0);
}
else
{
printf(“Computer Science n");
func();
}
return 0;
}
Output:
Computer Science
Hello World
Error: cannot proceed
60. getrlimit, setrlimit
Every process has a set of resource limits, some of which can be queried and changed by the
getrlimit and setrlimit functions.
#include <sys/resource.h>
int getrlimit(int resource, struct rlimit *rlptr);
int setrlimit(int resource, const struct rlimit *rlptr);
Both return: 0 if OK, nonzero on error.
Each call to these two functions specifies a single resource and a pointer to the following structure:
struct rlimit
{
rlim_t rlim_cur; /* soft limit: current limit */
rlim_t rlim_max; /* hard limit: maximum value for rlim_cur */
};
61. getrlimit, setrlimit
Three rules govern the changing of the resource limits.
A process can change its soft limit to a value less than or equal to its hard limit.
A process can lower its hard limit to a value greater than or equal to its soft limit.
Only a superuser process can raise a hard limit.
66. Process Identifiers
Every process has a unique process ID, a non negative integer
Special processes :
process ID 0 : scheduler process also known as swapper.
process ID 1: init process.
process ID 2: pagedaemon responsible for virtual memory pagging.
68. fork()
The only way a new process is created by UNIX kernel is when an existing process calls the fork function
#include <sys/types.h>
#include <unistd.h>
pid_t fork (void);
The new process created by fork is called child process
The function is called once but returns twice
The return value in the child is 0
The return value in parent is the process ID of the new child
The child is a copy of parent
Child gets a copy of parents text, data , heap and stack
Instead of completely copying we can use COW copy on write technique
69. Properties inherited by child are:
Real user ID, group ID, effective user ID, effective group ID
Supplementary group ID
Process group ID
Session ID
Controlling terminal
set-user-ID and set-group-ID
Current working directory
Root directory
File mode creation mask
Signal mask and dispositions
The close-on-exec flag for any open file descriptors
Environment
Attached shared memory segments
Resource limits
70. The difference between the parent and child
The return value of fork
The process ID
Parent process ID
The values of tms_utime , tms_stime , tms_cutime , tms_ustime is 0 for child
file locks set by parent are not inherited by child
Pending alarms are cleared for the child
The set of pending signals for the child is set to empty set
71. vfork()
#include <sys/types.h>
#include <unistd.h>
pid_t vfork (void);
It is same as fork
It is intended to create a new process when the purpose of new process is to exec a new
program
The child runs in the same address space as parent until it calls either exec or exit
vfork guarantees that the child runs first , until the child calls exec or exit.
72. No. FORK() VFORK()
1.
In fork() system call, child and parent process have separate
memory space.
While in vfork() system call, child and parent process share same
address space.
2.
The child process and parent process gets executed
simultaneously.
Once child process is executed then parent process starts its
execution.
3. The fork() system call uses copy-on-write as an alternative. While vfork() system call does not use copy-on-write.
4.
Child process does not suspend parent process execution in
fork() system call.
Child process suspends parent process execution in vfork() system
call.
5. Page of one process is not affected by page of other process. Page of one process is affected by page of other process.
6. fork() system call is more used. vfork() system call is less used.
7. There is wastage of address space. There is no wastage of address space.
8.
If child process alters page in address space, it is invisible to
parent process.
If child process alters page in address space, it is visible to parent
process.
73. Wait and waitpid function
When a child id terminated the parent is notified by the kernel by sending a SIGCHLD signal
The termination of a child is an asynchronous event
The parent can ignore or can provide a function that is called when the signal occurs
The process that calls wait or waitpid can
1. Block
2. Return immediately with termination status of the child
3. Return immediately with an error
74. Wait and waitpid function
#include <sys/wait.h>
#include <sys/types.h>
pid_t wait (int *statloc);
pid_t waitpid (pid_t pid, int *statloc , int options );
Statloc is a pointer to integer
If statloc is not a null pointer ,the termination status of the terminated process is stored in the
location pointed to by the argument
The integer status returned by the two functions give information about exit status, signal
number and about generation of core file
Macros which provide information about how a process terminated
1. Pid == -1 – waits for any child
2. Pid > 0 – waits for child whose process ID equals pid
3. Pid == 0 – waits for child whose process group ID equals that of calling process
4. Pid < -1 – waits for child whose process group ID equals to absolute value of pid
75. Race Condition
Race condition occurs when multiple process are trying to do something with shared data and
final out come depends on the order in which the processes run.
the fork function is the lively breeding ground for race conditions.
we cannot predict which process runs first.
what happens after the process starts running depends on the Operating system (system load
and scheduling algorithm ).
76. #include <sys/types.h>
static void charatatime(char *);
int main(void)
{
pid_t pid;
if ( (pid = fork()) < 0)
err_sys("fork error");
else if (pid == 0)
{
charatatime("output from childn");
}
else
{
charatatime("output from parentn");
}
exit(0);
}
static void
charatatime(char *str)
{
char *ptr;
int c;
setbuf(stdout, NULL);
/* set unbuffered */
for (ptr = str; c = *ptr++; )
putc(c, stdout);
}
77. exec functions
Exec replaces the calling process by a new program
The new program has same process ID as the calling process
No new program is created , exec just replaces the current process by a new
program.
exec merely replaces the current process- its text, data, heap and stack
segment with the brand new program from the disk.