簡體   English   中英

在cmd中暫停\\凍結和取消凍結

[英]pause in cmd \ Freeze and UnFreeze

我需要cmd中的命令,該命令的作用類似於暫停,但我可以編寫代碼以繼續。 例如

system("pause");
some lines of code;` 

system("pause")在於,直到用戶按下sth,“某些代碼行”才起作用。 我想用一些命令繼續執行cmd。

如果可以避免,請勿使用system() 它很粗糙,容易出錯且不可移植。

C11引入了線程支持,包括thrd_sleep() 那應該是您的首選解決方案(如果編譯器安裝程序支持)。

如果您的編譯器供應商支持C11,管不着他。 那個標准現在已經快四年了。

WinAPI定義了Sleep()函數:

VOID WINAPI Sleep(
  _In_  DWORD dwMilliseconds
);

此函數使線程放棄其剩余時間片,並在基於dwMilliseconds的值的間隔內變得無法運行。

#include <windows.h>

int main()
{
    Sleep( 5000 ); // pause execution for at least 5 seconds
    some_lines_of_code;
    return 0;
}

我想要一些可以運行代碼但僅在我授予其權限時才更新cmd的代碼。

如果我理解正確, 那么代碼將產生您不希望在按下鍵之前顯示的輸出。 如果您不介意分頁輸出,則可以使用類似

        FILE *stream = popen("PAUSE<CON&&MORE", "w");

並讓代碼輸出流(使用fprintf(stream, ...)等)。

我認為您正在尋找的是一種檢查stdin包含准備讀取的數據的方法。 您想使用一些非阻塞異步 I / O,以便您可以在可用時讀取輸入,並在此之前執行其他任務。

您不會在標准C中找到有關非阻塞/異步I / O的全部內容,但是在POSIX C中,您可以使用fcntlSTDIN_FILENO設置為非阻塞。 舉例來說,這是一個程序,提示您按Enter鍵(如pause操作)和忙循環,從而讓您的代碼在等待按鍵(ahemm,byte,由於從技術上講stdin文件 ):

#include <stdio.h>
#include <fcntl.h>
int main(void) {
    char c;
    puts("Press any key to continue...");
    fcntl(STDIN_FILENO, F_SETFL, fcntl(STDIN_FILENO, F_GETFL, 0) | O_NONBLOCK);
    while (read(STDIN_FILENO, 1, &c) != 1 && errno == EAGAIN) {
        /* code in here will execute repeatedly until a key is struck or a byte is sent */
        errno = 0;
    }
    if (errno) {
        /* code down here will execute when an input error occurs */
    }
    else {
        /* code down here will execute when that precious byte is finally sent */
    }
}

那是非阻塞的I / O。 其他選擇包括使用異步I / O或額外的線程。 您可能應該為此任務特別使用非阻塞I / O或異步I / O(即epollkqueue ); 僅使用額外的線程來確定何時將字符發送到stdin可能太重了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM