c - 父进程无限循环使用fork()后不更新屏幕

标签 c unix fork ncurses

我需要编写使用 fork() 创建 2 个进程的 UNIX 应用程序,这两个进程都在屏幕上的不同位置打印当前时间。子进程结束后,父进程必须停止工作。我写了这段代码:

#include <ncurses.h>
#include <unistd.h>
#include <time.h>
#include <wait.h>
#include <sys/types.h>

struct Point2
{
    int X;
    int Y;
};

int kbhit()
{
    //getch() implementation
}

void printTime(const struct Point2 pt, const char* st)
{
    char buf[255];
    time_t rawtime;
    struct tm * timeinfo;

    time (&rawtime);
    timeinfo = localtime(&rawtime);
    sprintf(buf, "%s: %02d:%02d:%02d", st, timeinfo->tm_hour,
            timeinfo->tm_min, timeinfo->tm_sec);
    mvaddstr(pt.Y, pt.X, buf);
    refresh();
}

void childp(pid_t pid, const struct Point2 pt)
{
    while(kbhit() != 27)
    {
        printTime(pt, "CHLD");
        usleep(1000);
    }
}

void parentp(pid_t pid, const struct Point2 pt)
{
    struct Point2 newp = {pt.X, pt.Y + 1};
    while(1)
    {
        int stat;
        waitpid(pid, &stat, WNOHANG);
        if(WIFEXITED(stat) != 0)
            break;

        printTime(newp, "PARN");
            usleep(1000);
    }
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        printf("unable to load XY position for clock.\n");
        return 1;
    }

    initscr();
    refresh(); // <-- this refresh

    struct Point2 opt;
    opt.X = atoi(argv[1]);
    opt.Y = atoi(argv[2]);

    pid_t pid;
    pid = fork();

    switch(pid)
    {
        case -1:
            printw("Error");
            _exit(0);
        case 0:
            childp(pid, opt);
            break;
        default:
        parentp(pid, opt);
            break;

    }
    endwin();
    return 0;
}

程序启动后,输出一次“CHLD”和“PARN”时间,然后从子进程正确更新“CHLD”时间,但父进程的输出不变。此外,如果我评论 main() 中的 refresh() 调用,“PARN”时间字符串根本不会显示。所以我的问题是:为什么父进程不更新屏幕?

更新。我几乎删除了父函数循环中的所有代码,现在它看起来像:

void parentp(pid_t pid, const struct Point2 pt)
{
    struct Point2 newp = {pt.X, pt.Y + 1};
    while(1)
    {
        printTime(newp, "PARN");
    }
}

还是不行

最佳答案

waitpid(pid, &stat, WNOHANG); 工作正常。我不知道为什么,但问题出在 mvaddstr(); 我将其更改为 printw() 瞧,它成功了!也许这是因为 mvaddstr(); 没有更新整个屏幕。另一种方法是在调用 fork() 之前绘制 PARN 和 CHLD 时间,但我认为这不是简单也不优雅的解决方案。使用 printw()。

关于c - 父进程无限循环使用fork()后不更新屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18642865/

相关文章:

c++ - C中的mysql聚合UDF(用户定义函数)

c - mq_receive 抛出错误,提示消息太长

c - 如何在 Linux C 中从库和地址中获取函数名

c - 如何获取文件的创建时间和最后写入时间

c - 需要知道 fork 是如何工作的吗?

c++ - macOS 上的 .so 和 .dylib 有什么区别?

java - 正则表达式问题,转义引号

linux - 在 shell 脚本中有没有一种方法,如果 [ &lt;script exits with non-0 value> ] then;做<某事>

子进程执行顺序似乎是错误的,但有效

c - fork() 父子进程的输出