2

我想在 linux gcc 上编写一个 C++ 程序,这样时间应该显示在右上角(不断变化)并且还可以让其他进程继续进行。

例如:

我希望时间显示在右上角,还想在同一屏幕上执行一些操作,例如基本计算...

. 我知道使用此代码段连续显示时间

#include<iostream.h>
int main()
{
while(1)
{
system("clear");
system("date +%r&");
sleep(1); 
}
return 0;
}

但每次,1)它清除屏幕,所以屏幕上的其他指令也被清除 2)我也想知道如何让两个进程同时运行?

使用 bg 等会有所帮助吗?

4

4 回答 4

2

There are two parts to your question.

First part: how to output time at a fixed location without disrupting other output on the screen.

Low-level approach:

High-level approach: use a text-based UI library, such as curses/ncurses.


Second part: how to update the time display in parallel to other activities.

In the simple case, you can just call time update function periodically from some places in your code you know will be executed regularly enough.

In the more complicated case, you will need to update time from a separate thread of execution. There is a lot said about multithreading, including on this site; unfortunately I can't recommend any specific introductory material offhand, but there are many.

[EDIT] In case you just want to run another program in the background, as @ecatmur suggests, you don't need threads; just use system("program &"), or fork+exec on Unix-ish systems and _spawn on Windows.

于 2012-08-02T15:21:15.893 回答
1

这是一个显示时间的。

#include <windows.h>
#include <conio.h>
#include <stdio.h>
#include<time.h>



int ch=0;
time_t now;

void gotoxy(int x, int y)
{
    COORD coord;
    coord.X = x; coord.Y = y;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
    return;
}

void setcolor(WORD color)
{
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),color);
    return;
}

void clrscr()
{
    COORD coordScreen = { 0, 0 };
    DWORD cCharsWritten;
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    DWORD dwConSize;
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

    GetConsoleScreenBufferInfo(hConsole, &csbi);
    dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
    FillConsoleOutputCharacter(hConsole, TEXT(' '), dwConSize, coordScreen, &cCharsWritten);
    GetConsoleScreenBufferInfo(hConsole, &csbi);
    FillConsoleOutputAttribute(hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten);
    SetConsoleCursorPosition(hConsole, coordScreen);
    return;
}

void getkey(void)
{
  if (kbhit())
  {
    ch=getch();

  }
}



int main(void)
{



    while (ch!=27)
    {
        getkey();   
        time(&now);

        gotoxy(50,1) ;
        setcolor(31);
        printf("%s", ctime(&now));
        setcolor(0);
    }

    setcolor(7);
    clrscr();

    gotoxy(2,23) ;
    return 0;

}
于 2012-08-05T14:01:10.700 回答
0

这是我在 C++ 屏幕的某个位置写东西的问题和答案, 在不使用 Windows 句柄的情况下更改光标位置。Qbasic模仿慢

这是@pumpkins 的线程问题 在线程 中运行函数

于 2012-08-03T12:13:22.807 回答
0

这不是一个小问题,因为在 Unix 下,程序在运行时会完全控制终端,这意味着您运行的任何程序都会假设它可以使用您显示时钟的空间,并且会进一步假设当它将光标定位在特定位置时,它将保持在那里。

让其他程序避开特定区域的唯一方法是首先不让他们访问终端,而是给他们一个伪终端并解释他们写入的所有内容(这就是两者xtermscreen工作方式);这很重要,因为还有很多控制序列用于设置前景色和背景色、重新定位光标、更改自动滚动的区域等)。

于 2012-08-03T12:31:39.780 回答