有一个程序可以逐渐读取登录名和密码。我的程序调用这个并通过 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/