c - 如何写入来自父进程的 getpass() 输入?

标签 c linux input passwords popen

假设我有以下短程序,我将其称为Parent.c

#include <unistd.h>
#include <stdio.h>
#include <string.h>

int main(){
    char buffer[100];
    memset(buffer, '\0', 100);
    scanf("%s", buffer);
    printf("%s\n", buffer);

    FILE* child =  popen("./child","w");
    fwrite(buffer, 1, strlen(buffer), child);
    pclose(child);

}

现在child.c有两种情况。

案例一:

#include <unistd.h>
#include <stdio.h>
#include <string.h>

int main(){
    char buffer[100];
    memset(buffer, '\0', 100);
    scanf("%s", buffer);
    printf("%s\n", buffer);
}

案例二:

#include <unistd.h>
#include <stdio.h>
#include <string.h>

int main(){
    char* password = getpass("");
    printf("%s\n", password);

}

在第一种情况下,如果我运行 ./Parent,然后键入“Hello World”,我会得到两个“Hello World”的回显。一个来自子程序,一个来自父程序。

在第二种情况下,如果我运行 ./Parent,然后键入“Hello World”,我得到一个“Hello World”的回显,然后从子进程得到一个输入提示。 如果我随后在此提示符下键入“Goodbye”,我将收到“Goodbye”的回显。

如何修改 Parent.c 以在案例 2 中获得当前在案例 1 中发生的相同行为?

最佳答案

简单的答案是:你不能。

来自getpass manual page :

The getpass() function opens /dev/tty (the controlling terminal of the process), outputs the string prompt, turns off echoing, reads one line (the "password"), restores the terminal state and closes /dev/tty again.

这意味着它直接从终端设备读取,而不是从标准输入。

关于c - 如何写入来自父进程的 getpass() 输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15152386/

相关文章:

c - C语言编程中的数据库

c++ - 将char数组传递给exec *()系列函数后,如何释放它们的内存

linux - 哪个实用程序产生 "Poky (Yocto Project Reference Distro) 2.6.1 (none)/dev/console"

linux - 我无法正确修改内核模块中的 ICMP 流量

linux - 如何将命令行脚本包装到 ./sh 文件

javascript - 如何获取 &lt;input type ="number"> 字段的原始值?

C 指针在函数中引用另一个指针

c - 为什么生成此代码以取消引用浮点指针?

java - 带循环的输入和输出

javascript - Opera 中的输入类型文件