首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何创建后台进程块,用于输入shell的`bg`命令?

如何创建后台进程块,用于输入shell的`bg`命令?
EN

Stack Overflow用户
提问于 2018-08-06 03:52:04
回答 1查看 273关注 0票数 1

出于安全控制的目的,我正在实现我自己的代码片段。它通常在后台运行,但在超时时需要接管当前终端,显示消息,收集用户输入,并对用户输入做出反应。

等待超时很容易。当sleep是活动程序时,收集用户输入很容易。防止shell窃取我刚才试图收集的用户输入并不容易。

我有理由相信"What if two programs did this?"并不适用。如果另一个程序在我们等待输入时被触发,这并不是很糟糕。如果用户想要干扰安全检查,有比这更简单的方法。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-06 03:52:04

需要进程组控制。如果您不知道作业控制是使用进程组控制实现的,就不容易发现这一点。shell在它们自己的进程组中启动后台进程,bgfg命令切换允许从终端读取哪个进程组。所有其他进程都会阻止从终端读取数据。

代码语言:javascript
复制
#include <unistd.h>

    sleep(600); /* triggering condition goes here */
    pid_t pgid = tcgetpgrp(0);
    pid_t pid;
    if ((pid = fork()) == 0) { /* Need to fork to safely create a new process group to bind to the terminal -- otherwise we might be in the same process group as we started in */
        pid_t npid = getpid();
        setpgid(npid, npid); /* create new process group and put us in it */
        pid_t pid2;
        if ((pid2 = fork() == 0) { /* what? another process */
            setpgid(getpid(), pgid);
            tcsetpgid(0, getpid()); /* set active process group */
            _exit(0);
        }
        if (pid2 > 0) {
            int junk;
            waitpid(pid2, &junk, 0);
        }
        struct termios savedattr;
        struct termios newattr;
        tcgetattr(0, &savedattr);
        newattr = savedattr;
        newattr.c_lflag |= ICANON | ECHO;
        tcsetattr(0, TCSANOW, &newattr); /* set sane terminal state */
        printf("\nHi there. I'm the background process and I want some input:");
        char buf[80];
        fgets(buf, 80, stdin);
        /* Do something with user input here */
        tcsetattr(0, TCSANOW, &savedattr); /* restore terminal state */
        tcsetpgrp(0, pgid); /* restore terminal owner -- only possible if the existing owner is a live process */
    } else {
        if (pid > 0) {
            int junk;
            waitpid(pid, &junk, 0);
        }
    }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51697742

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档