Justplayit94
Justplayit94

Reputation: 423

Linux Pipes and Redirecting output

I'm trying to write a linux program using pipes, but so far I've encountered a major problem. When I try to run this, it seems it either duplicates the answers, or doesnt give me an answer at all. So far I'm trying to use a pipe, the parent gets a string from the keyboard, and compares it to see if matches any other commands, momentarily its only the "login" command. But it doesnt work as it doesnt show me a fail or success message. I've been fiddeling with the code, but sometimes it's repeating the answer several time, like it's executing the child several times. Can someone explain me why its happening? Thx

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>


int fd[2], nbytes;
pid_t childpid;
char input[12];
char readbuffer[80];
int log_variable;
int pid; 


int compare(char str1[], char str2[]){
if(strlen(str1) == strlen(str2))
{int i;
for( i=0; i<strlen(str1); i++){
if(str1[i] != str2[i])
return 0;
return 1;
}
}
}


int test(char argument[]){//test function
pipe(fd);

switch(childpid=fork()){

case -1:
perror("fork -1\n");
exit(1);


case 0://child
close (fd[1]);

int nbytes = read(fd[0], readbuffer, sizeof(readbuffer));


if(compare(readbuffer, "login") == 1){

return 1;
}

else if(compare(readbuffer, "login") == 0){
return 0;

}
exit(1);



default:
//parent
close(fd[0]);
write(fd[1], argument, sizeof(argument));
while(wait(NULL)!=-1);

}

}
main(){

while(1){
printf("Insert command: \n");
scanf("%s", input);

logs=(test(input));
if(logs == 1) {printf("success\n"); break;} 
else if(logs == 0) {printf("fail\n"); continue;}
}

return 0;
}

Upvotes: 0

Views: 54

Answers (1)

Sam Liao
Sam Liao

Reputation: 46013

a couple of problems for your code with a quick look:

  • compare function doesn't return value if length not equal.
  • test() function may get called twice in one process, which means fork more times.
  • the test() internally for the child will return to the main, also parent will return to main ... get things more complicated here (the child may fork a third time ...)

Use "strace -F" can give you a much better view what things happened behind.

Upvotes: 1

Related Questions