Is There a Decent Wait Function in C++

Is there a decent wait function in C++?

you can require the user to hit enter before closing the program... something like this works.

#include <iostream>
int main()
{
std::cout << "Hello, World\n";
std::cin.ignore();
return 0;
}

The cin reads in user input, and the .ignore() function of cin tells the program to just ignore the input. The program will continue once the user hits enter.

Link

Is there a wait function in C++?

Since C++11, you might use std::this_thread::sleep_for

using namespace std::chrono_literals;

std::this_thread::sleep_for(250ms);

Is it possible to wait a few seconds before printing a new line in C?

Well the sleep() function does it, there are several ways to use it;

On linux:

#include <stdio.h>
#include <unistd.h> // notice this! you need it!

int main(){
printf("Hello,");
sleep(5); // format is sleep(x); where x is # of seconds.
printf("World");
return 0;
}

And on windows you can use either dos.h or windows.h like this:

#include <stdio.h>
#include <windows.h> // notice this! you need it! (windows)

int main(){
printf("Hello,");
Sleep(5); // format is Sleep(x); where x is # of milliseconds.
printf("World");
return 0;
}

or you can use dos.h for linux style sleep like so:

#include <stdio.h>
#include <dos.h> // notice this! you need it! (windows)

int main(){
printf("Hello,");
sleep(5); // format is sleep(x); where x is # of seconds.
printf("World");
return 0;
}

And that is how you sleep in C on both windows and linux! For windows both methods should work. Just change the argument for # of seconds to what you need, and insert wherever you need a pause, like after the printf as I did. Also, Note: when using windows.h, please remember the capital S in sleep, and also thats its milliseconds! (Thanks to Chris for pointing that out)

how to use wait in C

The wait system-call puts the process to sleep and waits for a child-process to end. It then fills in the argument with the exit code of the child-process (if the argument is not NULL).

So if in the parent process you have

int status;
if (wait(&status) >= 0)
{
if (WEXITED(status))
{
/* Child process exited normally, through `return` or `exit` */
printf("Child process exited with %d status\n", WEXITSTATUS(status));
}
}

And in the child process you do e.g. exit(1), then the above code will print


Child process exited with 1 status

Also note that it's important to wait for all child processes. Child processes that you don't wait for will be in a so-called zombie state while the parent process is still running, and once the parent process exits the child processes will be orphaned and made children of process 1.

How do you add a timed delay to a C++ program?

In Win32:

#include<windows.h>
Sleep(milliseconds);

In Unix:

#include<unistd.h>
unsigned int microsecond = 1000000;
usleep(3 * microsecond);//sleeps for 3 second

sleep() only takes a number of seconds which is often too long.

What is a busy loop in C?

A busy loop is a loop which purposely wastes time waiting for something to happen. Normally, you would want to avoid busy loops at all costs, as they consume CPU time doing nothing and therefore are a waste of resources, but there are rare cases in which they might be needed.

One of those cases is indeed when you need to sleep for a long amount of time and you have things like signal handlers installed that could interrupt sleeping. However, a "sleep busy loop" is hardly a busy loop at all, since almost all the time is spent sleeping.

You can build a busy loop with any loop construct you prefer, after all for, while, do ... while and goto are all interchangeable constructs in C given the appropriate control code.

Here's an example using clock_nanosleep:

// I want to sleep for 10 seconds, but I cannot do it just with a single
// syscall as it might get interrupted, I need to continue requesting to
// sleep untill the entire 10 seconds have elapsed.

struct timespec requested = { .tv_sec = 10, .tv_nsec = 0 };
struct timespec remaining;
int err;

for (;;) {
err = clock_nanosleep(CLOCK_MONOTONIC, 0, &requested, &remaining);

if (err == 0) {
// We're done sleeping
break;
}

if (err != EINTR) {
// Some error occurred, check the value of err
// Handle err somehow
break;
}

// err == EINTR, we did not finish sleeping all the requested time
// Just keep going...
requested = remaining;
}

An actual busy loop would look something like the following, where var is supposedly some sort of atomic variable set by somebody else (e.g. another thread):

while (var != 1);

// or equivalent

while (1) {
if (var == 1)
break;
}

Needless to say, this is the kind of loop that you want to avoid as it is continuously checking for a condition wasting CPU. A better implementation would be to use signals, pthread condition variables, semaphores, etc. There are usually plenty of different ways to avoid busy looping.

Finally, note that in the above case, as @einpoklum says in the comments, the compiler may "optimize" the entire loop body away by dropping the check for var, unless it has some idea that it might change. A volatile qualifier can help, but it really depends on the scenario, don't take the above code as anything other than a silly example.

When does the wait() function (in LINUX) respond to interrupts?

When you install a signal handler with signal(), one of 2 things occur

  1. Most system calls get interrupted when a signal occurs, and sets errno to EINTR.
  2. Most system calls gets automatically restarted when a signal occurs (so they don't fail and set errno to EINTR).

Which of these 2 depends on your platform, on yours it's 2 (probably, you don't show any code that installs a signal handler.)

If you instead install a signal handler with sigaction(), you can control which behavior of 1 or 2 you want with the SA_RESTART flag.



Related Topics



Leave a reply



Submit