I have a C program where I can offer as input different commands. The commands are processed by children and the answers are send it back to the parent. One of my command is quit and one command is login. If I have as a input commands in this order : login and quit, the quit must pe introduced twice to close the program. Also the parent takes the input in a while loop and quit is supposed to close the program. Also I'm getting the result from the first login as answer.
If you know what could be, please let me know. Thanks! Have a great day!
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#define verde printf("\033[0;32m")
#define alb printf("\033[0m")
#define rosu printf("\033[0;31m")
#define blue printf("\033[1;34m")
typedef int bool;
#define true 1
#define false 0
int main(int argc, char **argv)
{
char *comanda = (char *)malloc(55);
bool loggedIn = false;
while (1)
{
blue;
printf("Insert the command: ");
alb;
fgets(comanda, 55, stdin);
if(strstr(comanda, "quit") != NULL)
{
exit(0);
}
if (strstr(comanda, "login : ") != NULL )
{
pid_t pid;
int fd[2];
if (pipe(fd) == -1)
{
rosu;
perror("Am esuat in a crea un pipe...");
exit(1);
}
if ((pid = fork()) == -1)
{
rosu;
perror("Child failed...");
exit(2);
}
else if (pid)
{
FILE *ptr;
close(fd[0]);
if ((ptr = fopen("users.txt", "r")) == NULL)
{
rosu;
perror("Failed to open users.txt ...");
exit(3);
}
char username[30];
bool gasit = false;
while (fgets(username, 30, ptr))
{
if (strstr(comanda, username) != NULL)
{
gasit = true;
break;
}
}
if (write(fd[1], &gasit, sizeof(bool)) == -1)
{
rosu;
perror("Failed to write in pipe...");
exit(4);
}
close(fd[1]);
}
wait(NULL);
bool raspuns;
close(fd[1]);
if (read(fd[0], &raspuns, sizeof(bool)) == -1)
{
rosu;
perror("Can't write from pipe...");
exit(5);
}
if (raspuns == true)
{
verde;
printf("Succes!\n");
alb;
}
else
{
rosu;
printf("Failed to login!\n");
alb;
}
close(fd[0]);
}
else if(strstr(comanda, "myfind : ") != NULL)
{
}
else if(strstr(comanda,"mystat : ")!=NULL)
{
}
else
{
rosu;
printf("Wrong command!\n");
alb;
}
}
return 0;
}