linux 将STDIN从脚本传递到二进制文件会导致重复输入

pod7payv  于 2022-11-02  发布在  Linux
关注(0)|答案(1)|浏览(117)

我有一个实现命令提示符菜单的程序:


# include <stdio.h>

# include <string.h>

int
main(int argc, char *argv[])
{
  char username[32] = {0};
  printf("Username: ");
  fgets(username, sizeof(username), stdin);
  username[strcspn(username, "\n")] = '\0';

  char password[32] = {0};
  printf("Password: ");
  fgets(password, sizeof(password), stdin);
  password[strcspn(password, "\n")] = '\0';

  printf("\nWelcome!\n");

  while (1)
  {
    char command_buffer[1024] = {0};

    printf("Enter one of the following commands (EDG, UED, SCS, DTE, AED, UVF, OUT): ");
    fgets(command_buffer, sizeof(command_buffer), stdin);
    // fgets() is returning NULL and not blocking
    // as pointed out by @Spikatrix, probably because standard input stream was closed?
    command_buffer[strcspn(command_buffer, "\n")] = '\0';
  }

  return 0;
}

我想自动传递用户名和密码,我已经尝试了以下每个选项,但都不起作用:


# username = "dev", password = "pass"

# Option1

{ echo "dev" & sleep 0.1; echo "pass"; } | ./example

# Option2

./example <<< $'dev\npass\n'

# Option3

(echo "dev\npass" | cat) | ./example

运行脚本后,example二进制文件正确地处理用户名和密码(当您进入菜单屏幕时)。但是,它只是不断地打印出菜单提示Enter one of the following commands (EDG, UED, SCS, DTE, AED, UVF, OUT):。这对我来说意味着一个换行符(或类似效果的字符)不断地被输入到程序中。

mitkmikd

mitkmikd1#

fgets()返回NULL,如果流被关闭,并且没有阻塞。这是重定向的情况。
由于您的程序不检查返回值,因此它会继续运行。

相关问题