fork,exec和从shell读取失败

时间:2018-09-04 22:37:26

标签: linux fork exec parent-child

我有以下一段代码,它们先执行fork(),然后执行execlp(),以执行子进程。

/*
 * Spawns a child process. Behaviour can be controlled using flag.
 * Limited to 2 arguments to a program, flag works on bit set.
 */
static void
spawn(const char *file, const char *arg1, const char *arg2, const char *dir, uchar flag)
{
    static char *shlvl;
    static pid_t pid;
    static int status;

    if (flag & F_NORMAL)
        exitcurses();

    pid = fork();
    if (pid == 0) {
        if (dir != NULL)
            status = chdir(dir);

        shlvl = getenv("SHLVL");

        /* Show a marker (to indicate nnn spawned shell) */
        if (flag & F_MARKER && shlvl != NULL) {
            printf("\n +-++-++-+\n | n n n |\n +-++-++-+\n\n");
            printf("Next shell level: %d\n", atoi(shlvl) + 1);
        }

        /* Suppress stdout and stderr */
        if (flag & F_NOTRACE) {
            int fd = open("/dev/null", O_WRONLY, 0200);

            dup2(fd, 1);
            dup2(fd, 2);
            close(fd);
        }

        if (flag & F_NOWAIT) {
            signal(SIGHUP, SIG_IGN);
            signal(SIGPIPE, SIG_IGN);
            setsid();
        }

        if (flag & F_SIGINT)
            signal(SIGINT, SIG_DFL);
        execlp(file, file, arg1, arg2, NULL);
        _exit(1);
    } else {
        if (!(flag & F_NOWAIT))
            /* Ignore interruptions */
            while (waitpid(pid, &status, 0) == -1)
                DPRINTF_D(status);

        DPRINTF_D(pid);
        if (flag & F_NORMAL)
            refresh();
    }
}

我正在尝试执行以下脚本(文件名:nscript):

#!/bin/sh

echo Press Enter to continue...
read arg

我将标志F_NORMAL | F_SIGINT传递给spawn()

但是,似乎输入从未到达脚本中的read,因此我不得不终止该程序:

$ ./nnn
Press Enter to continue...


^C^\fish: “./nnn” terminated by signal SIGQUIT (Quit request from job control with core dump (^\))

相关代码可在此处找到:https://github.com/jarun/nnn/blob/v1.9/nnn.c#L692-L748

要复制,

  1. 安装nnn
  2. 运行

    export NNN_SCRIPT=/usr/local/bin/nscript
    nnn
    
  3. R

非常感谢!

0 个答案:

没有答案