c - 通过 pipe() 系统调用 : how to imitate pressing enter (during the input) in terminal? 向子进程传输数据

标签 c linux input io

有一个程序可以逐渐读取登录名和密码。我的程序调用这个并通过 pipe() 系统调用重定向她的输入。它是这样工作的:

int main(void)
{
    int pipes[2];
    pipe(pipes);
    pid_t pid = fork();
    if (!pid)
    {
        close(pipes[1]); // close write-descriptor
        dup2(pipes[0], 0); // copy read-descriptor to 0, hence replace standard input with our pipe descriptor.
        execl(...);
    }
    else if (pid > 0)
    {
        close(pipes[0]);
        ...
        write(pipes[1], "username\n", 9); // transfer username (here is a problem)
        write(pipes[1], "password\n", 9); // transfer password (and here is one)
    }
    else
    { ... }
    return 0;
}

登录名和密码都已读入调用程序中的登录变量。我假设调用的程序是这样读的:

read(0, buff_login. 1024);
...
read(0, buff_password, 1024);
...

如果我们在终端中运行此程序并在输入登录后按下回车按钮,在调用的程序中,read() 系统调用将返回程序的控制权并将所有作为输入传递的内容写入缓冲区......然后它调用第二个 read() 来读取密码。

我如何使用管道描述符从我的程序中模仿这种行为?因为如果我将 '\n' 字符写入管道描述符,它不会影响调用程序中的 read() 系统调用,它会继续在登录缓冲区中读取。

最佳答案

如果有人对我如何解决这个问题感兴趣:解决方案是将 sleep(1) 放在两次 write() 调用之间。

关于c - 通过 pipe() 系统调用 : how to imitate pressing enter (during the input) in terminal? 向子进程传输数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54380302/

相关文章:

c - 为结果添加 fopen 时程序将无法运行

c - 使用 typedef struct 和使用内部数据的问题

c - C99 之前的 C 在 for 循环中没有初始声明的原因是什么?

linux - 从硬件本身查找原始 MAC 地址

javascript - 确定动态最小/最大值的数字百分比

asp.net - 是否需要对密码输入进行清理?

c - 如何生成给定大小的#define 列表

c - 用 C 以特定格式矩阵打印

linux - BASEDIR 环境变量未正确定义

linux - 在 shell 脚本 sh linux 中读取行