#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#define MAXLINE 256
#define MAX_PASSWORD 10

#define SUCCESS "Password verified\n"
#define INVALID "Invalid password\n"
#define NO_USER "No such user\n"

int main(void) {
  char user_id[MAXLINE];
  char password[MAXLINE];


  /* The user will type in a user name on one line followed by a password 
     on the next.
     DO NOT add any prompts.  The only output of this program will be one 
	 of the messages defined above.
     Please read the comments in validate carefully
   */

  if(fgets(user_id, MAXLINE, stdin) == NULL) {
      perror("fgets");
      exit(1);
  }
  if(fgets(password, MAXLINE, stdin) == NULL) {
      perror("fgets");
      exit(1);
  }

  if (strlen(user_id) > MAX_PASSWORD || strlen(password) > MAX_PASSWORD) {
      fprintf(stderr, "Error: User id or password is too long");
      exit(1);
  }

  int fd[2];

  if (pipe(fd) == -1){
      perror("pipe");
      exit(1);
  }

  int r = fork();
  if (r == -1){
      perror("fork");
      exit(1);
  }
  else if (r == 0){
      close(fd[1]);
      if (dup2(fd[0], STDIN_FILENO) == -1){
          perror("dup2");
          exit(1);
      }
      execl("./validate", "validate", NULL);
      perror("execl");
      exit(1);
  }
  else{
      if (close(fd[1] == -1)){
          perror("close");
          exit(1);
      }

      char result[MAX_PASSWORD];
      if (read(fd[0], result, MAX_PASSWORD) == -1){
          perror("close");
          exit(1);
      }

      int status;
      if (wait(&status) == -1){
          perror("wait");
          exit(1);
      }
      if (WIFEXITED(status)) {
          int exit_status = WEXITSTATUS(status);
          if (exit_status == 0) {
              printf(SUCCESS);
          }
          else if (exit_status == 2) {
              printf(INVALID);
          }
          else {
              printf(NO_USER);
          }
      }
  }

  return 0;
}

pipe input to another program