C ++ function works fine on Windows, but not Linux?

I am trying to write a simple C ++ function sleep(int millisecond)that will sleep with a program for a custom millisecond.

Here is my code:

#include <iostream>
#include <time.h>

using namespace std;

void sleep(unsigned int mseconds) {
    clock_t goal = mseconds + clock();
    while (goal > clock());
}

int main() {
    cout << "Hello World !" << endl;
    sleep(3000);
    cout << "Hello World 2" << endl;
}

The function sleep()works fine when I run this code on Windows, but it does not work on Linux. Can anyone understand what happened to my code?

+4
source share
4 answers

You can use the built-in function sleep(), which takes response time as seconds, not in milliseconds, and should include a standard library unistd.h, since the build-in function is sleep()defined in this library.

Try:

#include <iostream>
#include <unistd.h>

using namespace std;

int main() {
    cout << "Hello World !" << endl;
    sleep(3);   //wait for 3 seconds
    cout << "Hello World 2" << endl;
}

: R

+1
source

, , .

, , , , ( , "" , , , ), .

, clock() . clock() / , . .

, , man:

clock() , , CLOCKS_PER_SECs .

clock() , , -1.

.

getrusage (2), (7)

clock() ISO/IEC 9899: 1990 (`` ISO C90 '') 3 UNIX (`` SUSv3 '') , CLOCKS_PER_SEC .

, , ( ). "" 3 , sleep(3000000), sleep(3000).

+9

++ 11 sleep_for.

#include <chrono>
#include <thread>

void sleep(unsigned int mseconds) {
    std::chrono::milliseconds dura( mseconds);
    std::this_thread::sleep_for( dura );
}
+2

There is no standard C API for milliseconds on Linux, so you will need to use usleep. POSIX sleeptakes seconds.

0
source

All Articles