c - 如何使守护进程的子进程在 Linux 中交互?

标签 c linux

我想从守护进程中生成一个交互式进程。我怎样才能做到这一点?我尝试了以下代码片段:

int main (int argc, char *argv[])
{
    if (fork()) exit (EXIT_FAILURE) ;
    freopen("/dev/null","w",stderr) ;
    freopen("/dev/null","r",stdin) ;
    freopen("/dev/null","w",stdout) ;
    /*
     */
    if (fork()) exit (EXIT_FAILURE) ;
    pid_t shell_pgrp = getpgrp () ;
    pid_t my_pid = getpid () ;
    int shell_tty = isatty (fileno(stderr)) ?
        dup (fileno(stderr)) : open (ctermid(NULL), O_RDWR|O_NONBLOCK) ;
    shell_tty = fcntl (shell_tty,F_DUPFD,10) ;
    fcntl (shell_tty,F_SETFD,FD_CLOEXEC) ;
    if (shell_tty < 0) exit (EXIT_FAILURE) ;
    if ((shell_pgrp = tcgetpgrp (shell_tty)) != getpgrp()) {
        setpgid (my_pid,shell_pgrp) ;
    }
    if (shell_pgrp < 0) exit (EXIT_FAILURE) ;
    if ((shell_pgrp = tcgetpgrp (shell_tty)) == getpgrp()) {
        signal (SIGTTIN,SIG_IGN) ;
        signal (SIGTTOU,SIG_IGN) ;
        signal (SIGTSTP,SIG_IGN) ;
        signal (SIGHUP ,SIG_IGN) ;
        signal (SIGQUIT,SIG_IGN) ;
        signal (SIGQUIT,SIG_IGN) ;
        if (!tcsetpgrp (shell_tty,shell_pgrp)) {
            argv++ ;
            if (execv(argv[0],argv) < 0) {
                exit (EXIT_FAILURE) ;
            }
        }
    }
}

最佳答案

我自己从未尝试过,但我不认为复制标准文件 描述符将起作用。我相信您生成的进程需要获得一个新的控制终端。 This API 可能会对您有所帮助。

关于c - 如何使守护进程的子进程在 Linux 中交互?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6491490/

相关文章:

c - 指针子串数组

C程序打印奇怪的字符

c++ - OpenSSL 忽略自签名证书错误

linux - Ciphertext-Policy Attribute-Based Encryption toolkit "make"错误与 libgmp

linux - 获取目录中每个文件的 "Head"?

python - 尝试导入 pymc 时出错

Cygwin shell : $ make ex1 returns: "The system cannot find the specified file" on Windows 7

c - VS 编译器和 g++ 在结构体变量初始化方面的区别

linux - Bash:在变量内使用单引号

linux - 在 linux 上安装图形库