eswaat
eswaat

Reputation: 763

What happen at OS level when to want to write something into file?

What happen at OS level when to want to write something into file ? Any OS is fine but I am familiar with Linux so if somebody give me answer in Linux that would be great.

I know few things that will happen when we open a file for writing in C below is my rough code.

FILE *fp;
fp = fopen("/tmp/test.txt", "w+");
fputs("This is testing for fputs...\n", fp);

Upvotes: 5

Views: 1475

Answers (1)

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

Next, the sys_write kernel function is called. Go download a copy of the Linux kernel source, and have a look at it. You're looking for SYSCALL_DEFINE3(write... in fs/read_write.c.

sys_write will call fdget to basically get a struct file* pointer, and call vfs_write (in the same file).

Remember that write is a very generic syscall, that allows you to write data to any open file descriptor (which may not even be a file on disk, at all). In the struct file* is a pointer (f_op) to a number of function pointers. Since a "file" is a totally generic thing, these function pointers are what know how to do the actual writing, depending on the type of file. This provides a sort of "polymorphism", but in plain C code. So vfs_write will call file->f_op->write().

These calls will make their way down to the filesystem layer (in the fs/ directory). So again, it depends on what filesystem you have mounted (e.g. ext3, nfs, etc.)

Eventually they will make their way down to the block device layer, which is where raw reads/writes of block data to real hardware is done. Again, it depends on the device you have attached (e.g. PATA, SATA/SCSI, RAID, USB, network...)

The device-driver is where the actual communication with hardware will take place. This is where any DMA or memory-mapped I/O will occur.

This would probably be best described by a good book.

Upvotes: 7

Related Questions