- What does the sleep command do in Linux?
- So, what does the sleep command do in Linux?
- Sleep command syntax
- Sleep command examples
- How to use the Linux sleep command to pause a bash script
- How can I wake a process from sleep status via signal or /proc?
- 2 Answers 2
- Использование команды Sleep в скриптах Bash в Linux
- Примеры команды Sleep в Bash
- Команда sleep без суффикса считается в секундах
- Команда Sleep с суффиксом m, h или d
- Команда sleep с комбинацией секунд, минут, часов и дня
- Бонусный совет: спать меньше секунды
- What Are the Process States in Unix/Linux?
- In Unix/Linux operating systems, processes can be in one of the five following states. Let’s discuss these states in this article.
- RUNNING and RUNNABLE
- Sleeping
- How to Kill the Sleeping Process?
- STOPPED
- ZOMBIE
- How to Kill the ZOMBIE Process?
- How to know reason of a process going to sleep state and wake it up?
- 2 Answers 2
What does the sleep command do in Linux?
C an you explain to me the sleep command in Linux? I read somewhere that it can pause a bash shell script. How can I use the Linux sleep command to pause a bash script?
You can use sleep command to pause execution of shell scripts or commands for a given period on a Linux or Unix-like systems. This page explains syntax and usage of the sleep command in Linux operating systems.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | sleep command on Linux or Unix |
Est. reading time | 3 minutes |
So, what does the sleep command do in Linux?
- /bin/sleep is Linux or Unix command to delay for a specified amount of time.
- You can suspend the calling shell script for a specified time. For example, pause for 10 seconds or stop execution for 2 mintues.
- In other words, the sleep command pauses the execution on the next shell command for a given time.
- GNU version of sleep command supports additional options
- For example, suspend a bash shell script or command prompt for five seconds, type: sleep 5
- Common examples of sleep commands include scheduling tasks and delaying the execution to allow a process to start. Another usage is waiting until a wifi network connection available to stream large file over the network.
Sleep command syntax
The syntax for the sleep command is as follows:
sleep NUMBER[SUFFIX]
In addition to seconds, [SUFFIX] can be as follows on GNU/Linux:
- s for seconds (the default).
- m for minutes.
- h for hours.
- d for days.
Above options are only supported on GNU version of Linux and not on macOS/Unix/*BSD family of oses. Therefore, for non-GNU/Linux system try:
sleep 5
sleep 2
Sleep command examples
To sleep for 13 seconds, use:
sleep 13
For instance, sleep for 0.5 or 2.5 seconds too, try:
sleep 0.5
OR
sleep 2.5
So a floating point number allowed. However, sleep 2h30m not allowed. Want to sleep for 2 minutes? Try:
sleep 2m
Halt or sleep for 2 hours, use:
sleep 2h
First sleep for 8 hours and after that play music file named wake-up.mp3
sleep 8h && mplayer wake-up.mp3
How to use the Linux sleep command to pause a bash script
Let us see a simple example that pause script for 10 seconds.
Источник
How can I wake a process from sleep status via signal or /proc?
Many years ago I had an issue with Linux where processes would randomly go to sleep. Back then, I knew a trick with the /proc filesystem to trigger a wakeup of the process. I vaguely remember being able to do something like «echo R» >/proc/pid/stat but that doesn’t appear to be the right command.
There are lots of hits on the internet for «how do I wake a sleeping process?» and so many of the answers are «oh, just kill it!» I know there’s another way, but my memory is failing me now.
So far I’ve tried:
2 Answers 2
What do you mean by “sleep”?
If you mean state S (interruptible sleep), that means that the process is waiting for I/O. The process is currently engaged in a blocking system call. You can’t force it to “wake up” in a generic way — what would it do then? It’ll wake up when the input or output operation it wants to make is possible (e.g. when data is available to read, when a write channel becomes ready, etc.).
If you mean state T (stopped), that means that the process is currently suspended. You can unsuspend it by sending it a CONT signal (SIGCONT): kill -CONT PID .
Processes do not “randomly go to sleep”. They sleep when they have nothing to do. They get suspended if they receive a signal that stops them: SIGTSTP, SIGSTOP, SIGTTIN, SIGTTOU. These last two signals are sent by the terminal interface in the kernel when a background process tries to read from the terminal (resp. write to the terminal); if you aren’t aware of that, you might think that the process randomly stops. If that’s what happened, you need to bring it to the foreground; run fg in the shell from which you started that background job, with the right argument to indicate the job that the process is part of, e.g. fg %3 .
The stat* files in Linux’s /proc are read-only and I’m not aware of any time when they were writable. I don’t know what you could hope to write there. The data reported by this file is kernel-managed data, and some of it can be changed more or less directly by the process, but it isn’t something you can modify from the outside. For example you can’t magically make a process become runnable.
Источник
Использование команды Sleep в скриптах Bash в Linux
Главное меню » Операционная система Linux » Использование команды Sleep в скриптах Bash в Linux
Команда sleep в Linux – одна из самых простых команд. Как видно из названия, его единственная функция – спать. Другими словами, он вводит задержку на указанное время.
Таким образом, если вы используете команду sleep с x, то следующая команда может быть запущена только через x секунд.
Команда Sleep имеет простой синтаксис:
Здесь суффикс может быть:
Давайте посмотрим несколько примеров команды sleep.
Примеры команды Sleep в Bash
Хотя вы можете использовать его непосредственно в оболочке, команда sleep обычно используется для введения задержки в выполнение сценария bash. Мы собираемся показать использование команды sleep через примеры сценариев bash.
Команда sleep без суффикса считается в секундах
Предположим, вы хотите приостановить ваш bash-скрипт на 5 секунд, вы можете использовать режим sleep следующим образом:
В примере скрипта bash это может выглядеть так:
Если вы запустите его с помощью команды time, вы увидите, что скрипт bash на самом деле работал (немного) более 5 секунд.
Команда Sleep с суффиксом m, h или d
Вы можете указать время sleep в минутах следующим образом:
Это приостановит скрипт/оболочку на одну минуту. Если вы хотите отложить сценарий на несколько часов, вы можете сделать это с помощью опции h:
Даже если вы хотите приостановить скрипт на несколько дней, вы можете сделать это с помощью суффикса d:
Это может помочь, если вы хотите работать в разные дни или дни недели.
Команда sleep с комбинацией секунд, минут, часов и дня
Вы не обязаны использовать только один суффикс за раз. Вы можете использовать более одного суффикса, и продолжительность sleep является суммой всех суффиксов.
Например, если вы используете следующую команду:
Это заставит скрипт ждать 1 час 10 минут и 5 секунд. Обратите внимание, что суффикс s здесь по-прежнему необязателен.
Бонусный совет: спать меньше секунды
Вы могли заметить, что наименьшая единица времени в команде sleep – секунда. Но что если ваш bash-скрипт будет спать в течение миллисекунд?
Хорошо, что вы можете использовать с плавающей точкой (десятичные точки) с командой sleep.
Поэтому, если вы хотите ввести паузу в 5 миллисекунд, используйте ее следующим образом:
Вы также можете использовать десятичные точки с другими суффиксами.
Будет введена задержка в 1 час 37 минут и 30 секунд.
Мы надеемся, что вы не спали, читая эти примеры команды sleep -).
Если у вас есть вопросы или предложения, пожалуйста, не стесняйтесь спрашивать.
Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.
Источник
What Are the Process States in Unix/Linux?
In Unix/Linux operating systems, processes can be in one of the five following states. Let’s discuss these states in this article.
Join the DZone community and get the full member experience.
In Unix/Linux operating systems, processes can be in one of the following states:
- RUNNING and RUNNABLE
- INTERRUPTABLE_SLEEP
- Uninterruptable_Sleep
- Stop
- Zombie
Let’s discuss these states in this article.
RUNNING and RUNNABLE
When the CPU executes a process, it will be in a RUNNING state. When the process is not waiting for any resource and ready to be executed by the CPU, it will be in the RUNNABLE state.
Sleeping
The Sleeping state indicates the process is currently waiting on certain resources (like waiting on I/O, waiting on locks, application code making the process to sleep, etc.). There are two types of Sleeping processes:
- INTERRUPTABLE_SLEEP: When a process is in INTERRUPTABLE_SLEEP, it will wake up from the middle of sleep and process new signals sent to it.
- UNINTERRUPTABLE_SLEEP: When a process is in UNINTERRUPTABLE_SLEEP, it will not wake up from the middle of sleep even though new signals are sent to it.
How to Kill the Sleeping Process?
If the process is in the INTERRUPTABLE_SLEEP state, then issuing a SIGKILL signal (i.e., ‘kill -9’) to the process, will terminate the process immediately. On the other hand, if the process is in the UNINTERRUPTABLE_SLEEP state, then the issuing a SIGKILL signal will not terminate it immediately. The process will only terminate after it completes its sleep/waiting operation. Thus, if you would like to kill a process that is in the UNINTERRUPTABLE_SLEEP state for a prolonged period then you have to reboot the system; there is no other way.
STOPPED
The STOPPED state indicates that the process has been suspended from proceeding further. In Linux, when you issue the ‘Ctrl + Z’ command it will issue a SIGSTOP signal to the process. When the process receives this signal it will be suspended/stopped from executing further. When a process is in the STOPPED state, it will only handle SIGKILL and SIGCONT signals. SIGKILL signals will terminate the process, but the SIGCONT signal will put the process back into a RUNNING/RUNNABLE state.
ZOMBIE
A process will terminate when it calls a ‘system exit’ API or when someone else kills the process. When a process terminates, it will release all the data structures and the resources it holds. However, it will not release its slot in the ‘process’ table. Instead, the process will send a SIGCHLD signal to its parent process. Now, it’s up to the parent process to release the child process slot in the ‘process’ table. The process will be in a ZOMBIE state from the time the child process issues the SIGCHLD signal until the parent process releases the slot in the ‘process’ table.
How to Kill the ZOMBIE Process?
Issuing ‘kill -9’ on a ZOMBIE process ID will not affect it because the ZOMBIE process doesn’t exist. However, ZOMBIE Process can be killed by sending a SIGCHLD signal to the parent process, using the below kill command:
Источник
How to know reason of a process going to sleep state and wake it up?
When I do ‘top’ , I see my perl script process in ‘S’ state. Is there a way to know, what is making this perl process go in sleep state and ways to wake it up? Any way to debug to give more insights on lines in perl script making it go in ‘S’ state.
2 Answers 2
A process in S state is usually in a blocking system call, such as reading or writing to a file or the network, or waiting for another called program to finish.
You can use strace -p
to find out which system call is currently happening. It will produce output like
which means that the process is trying to write 4096 bytes starting with «foobar» to stdout (fd #1) but whatever it has been redirected into is busy and the output buffer is full.
Processes go to sleep states when they are waiting for something, usually I/O.
Your process will be in S state when it is doing reads and possibly writes that are blocking. Can also happen while waiting on semaphores or other synchronization primitives.
You can’t «wake it up» — it will only proceed when the data/resource it is waiting for becomes available.
This is all normal and expected, and not usually a problem. Typically, this «program» run on the command line with no file:
will spend most of its time in sleep state, which is good — you don’t want it to waste CPU while it’s waiting for user input.
If you think this is a problem, try changing the way you do your I/O (reading larger chunks, in nice multiples of the underlying device’s block size, doing memory mapped I/O, etc.).
Источник