Kraken
Kraken

Reputation: 24243

Kernel Code vs User Code

Here's a passage from the book

When executing kernel code, the system is in kernel-space execut- ing in kernel mode.When running a regular process, the system is in user-space executing in user mode.

Now what really is a kernel code and user code. Can someone explain with example?

Say i have an application that does printf("HelloWorld") now , while executing this application, will it be a user code, or kernel code.

I guess that at some point of time, user-code will switch into the kernel mode and kernel code will take over, but I guess that's not always the case since I came across this

For example, the open() library function does little except call the open() system call. Still other C library functions, such as strcpy(), should (one hopes) make no direct use of the kernel at all.

If it does not make use of the kernel, then how does it make everything work?

Can someone please explain the whole thing in a lucid way.

Upvotes: 5

Views: 3253

Answers (1)

Alexey Frunze
Alexey Frunze

Reputation: 62106

There isn't much difference between kernel and user code as such, code is code. It's just that the code that executes in kernel mode (kernel code) can (and does) contain instructions only executable in kernel mode. In user mode such instructions can't be executed (not allowed there for reliability and security reasons), they typically cause exceptions and lead to process termination as a result of that.

I/O, especially with external devices other than the RAM, is usually performed by the OS somehow and system calls are the entry points to get to the code that does the I/O. So, open() and printf() use system calls to exercise that code in the I/O device drivers somewhere in the kernel. The whole point of a general-purpose OS is to hide from you, the user or the programmer, the differences in the hardware, so you don't need to know or think about accessing this kind of network card or that kind of display or disk.

Memory accesses, OTOH, most of the time can just happen without the OS' intervention. And strcpy() works as is: read a byte of memory, write a byte of memory, oh, was it a zero byte, btw? repeat if it wasn't, stop if it was.

I said "most of the time" because there's often page translation and virtual memory involved and memory accesses may result in switched into the kernel, so the kernel can load something from the disk into the memory and let the accessing instruction that's caused the switch continue.

Upvotes: 5

Related Questions