0

In C, how does the sleep function work? At the background is a while loop created? Or for loop? I would like to know exactly what lib does, how could I recreate a sleep in a simple way without having to use lib?

Henrique Ramos
  • 714
  • 8
  • 25
  • 1
    The exact implementation is depending on toolset and target architecture and operating system. If you look at some implementation you should expect to see some code to configure some wakeup timer and then give the CPU to some other process. A loop would only be last option if you don't have any OS or timers at all. – Gerhardh Dec 22 '20 at 13:40
  • 1
    Start by reading the man pages for [sleep()](https://linux.die.net/man/3/sleep) Do a search for Linux implementation of `sleep()`. – ryyker Dec 22 '20 at 13:40
  • 1
    If you need search terms, ["busy waiting"](https://en.wikipedia.org/wiki/Busy_waiting) is typically the terminology associated with waiting/sleeping by looping tightly. – gspr Dec 22 '20 at 13:41
  • 2
    dupe of [How does sleep() work?](https://stackoverflow.com/questions/4911739/how-does-sleep-work), easy to find. – underscore_d Dec 22 '20 at 13:44
  • @underscore_d not exactly – Henrique Ramos Dec 22 '20 at 13:45
  • @HenriqueRamos Explain why not then. – underscore_d Dec 22 '20 at 13:46
  • @underscore_d He explains how it works under the hood but does not explain how it is implemented, my doubt is how it would be to implement my own sleep function – Henrique Ramos Dec 22 '20 at 13:51
  • 1
    @HenriqueRamos The other question has multiple answers, one of which says "These are system calls. Lookup the implementation in Open-source code like in Linux or Open BSD." That is basically the same answer that you would get here, and it wouldn't really be on-topic for someone just to paste some such implementation here and talk through it – underscore_d Dec 22 '20 at 13:53

1 Answers1

3

It's not implemented with a loop of any kind (that would waste energy occupying a core when you're doing nothing); it's a system call in which you tell the OS to suspend the current thread and wake it after the interval has elapsed (the exact mechanism used varies by OS). Reimplementing it yourself is ultimately going to depend on a system call and/or signals in some way; don't bother, just use sleep (or nanosleep, or Sleep, depending on OS).

ryyker
  • 22,849
  • 3
  • 43
  • 87
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • But how do I make this system call manually? – Henrique Ramos Dec 22 '20 at 13:44
  • @HenriqueRamos Why do you (think you) want to do that? What are you actually trying to achieve? If the answer is platform independence/abstraction, then use a library that handles that for you, rather than manually calling into the OS, is usually the correct answer (unless e.g. you're coding for an embedded platform or something). But in this case, the C Standard Library is already doing that, so there's no more needed. – underscore_d Dec 22 '20 at 13:45
  • How? Preferrably "not". Otherwise you implement it as part of the Operating System you are creating - which I doubt. You would have to implement that piece of software which is aware of the events you can wait for and for the scheduling of other software parts (tasks, threads, ISRs), which are those things which are executed while the caller is `sleep()`ing; that is the point of `sleep()` after all. If you are aware of that then you are writing the OS (or part of it). – Yunnosch Dec 22 '20 at 13:45
  • @HenriqueRamos: It differs by OS. The whole reason these library functions exist is to abstract away incredibly non-portable behaviors into portable APIs. You're welcome to look up the source code for the implementation of `sleep` on your particular system, but "how do I make a system call?" is both too broad (the answer differs *everywhere*) and already well-answered for any given OS (just look up the system call documentation for that OS). – ShadowRanger Dec 22 '20 at 13:45
  • Just to understand how it works "under the hood", I'm new in C – Henrique Ramos Dec 22 '20 at 13:47
  • 3
    Step 1: Assume that under the hood there is an OS doing it for you. Step 2: Do lots and lots of other things in your career. Step 3: Read up on Operating System implementations, when you have collected experience with the basics of programming, by doing step 1 and step 2. – Yunnosch Dec 22 '20 at 13:50
  • 3
    @HenriqueRamos If you are new to C you should focus how it works on the surface and then only sneak into how it is implemented. You should only do the second step if you don't consider yourself "new to C" anymore but "rather experienced" instead. – Gerhardh Dec 22 '20 at 13:50
  • 2
    @HenriqueRamos you can't in "pure" C to directly call a system call. You can directly call a system call in assembly. But what still wouldn't answer your "how it's implemented under the hood" because the call is just setting some registers and then calling `syscall`, very simple. The actual work is done in the OS. To understand that you need a lot of experience in C and OS programming. – bolov Dec 22 '20 at 13:52
  • As I am learning C with Ecole 42, they prevent me as much as possible from using ready-made functions like printf, strcpy ... we need to create everything with other simpler functions like write(). Thinking about it, I wondered what it would be like to recreate sleep, but from what you say it goes far beyond C. So, I will continue learning about C. – Henrique Ramos Dec 22 '20 at 13:56
  • @HenriqueRamos: `sleep` is already roughly equivalent to `write`; one of the most barebones API wrapping a system call you can get. `printf` does user level work, then defers to `write`; `strcpy` is entirely user-level. `sleep` is almost entirely OS level; it may involve some user-level setup, but the key work requires OS assistance, just like `write`. – ShadowRanger Dec 22 '20 at 13:59
  • @ShadowRanger Both are called in unistd.h, can I consider that unistd are functions closer to the system level then? Would recreating sleep be completely different from recreating printf with write? – Henrique Ramos Dec 22 '20 at 14:01
  • "_As I am learning C with Ecole 42, they prevent me as much as possible from using ready-made functions like printf, strcpy"_ and there it is. IMO that sounds exactly the wrong way around. – underscore_d Dec 22 '20 at 14:06
  • Ask your teacher. At a guess they either agree to allow sleep() or they will tell you that sleep() is not needed for your assignments. Which I guess, if you are not explicitly doing multi-tasking/multithreading. I bet quite a lot that they do not really expect you to implement it. – Yunnosch Dec 22 '20 at 14:07
  • @HenriqueRamos: "Would recreating `sleep` be completely different from recreating `printf` with `write`?" Yep. `sleep` and `write` are thin wrappers for system calls (equally annoying/semi-impossible to recreate from raw user-space C code). `printf` is typically a user-space wrapper around `fwrite`, which is in turn a user-space buffered wrapper around `write`. [`unistd.h` is for POSIX C API functions for the per-OS system calls](https://en.wikipedia.org/wiki/Unistd.h); if something is defined there, it's part of the POSIX OS API (not C standard), and it's generally a thin syscall wrapper. – ShadowRanger Dec 22 '20 at 15:21
  • An example of an analogous case for `printf` wrapping `write` for `sleep` would be if you wrote some wrapper function like `void sleep_poll(atomic_int *observed, int value, unsigned interval)` where you passed it the address of some `int` you expect to be updated (by another thread or a signal handler or the like) the value you want it to have, and a period of time between checks. The body would be something like `while (*observed != value) { sleep(interval); }`; it's doing user-level stuff powered by the `sleep` syscall, just like `printf` is doing user-level formatting powered by `write`. – ShadowRanger Dec 22 '20 at 15:27
  • @ShadowRanger ty! I understand now – Henrique Ramos Dec 23 '20 at 09:07