-
Garbage appearing
Hey guys,
I'm once again sending a phrase (in this case, it's only a simple command) through my pipe and when server receives it instead of printing it it prints this a square with 0's and 1's inside (wtf?).
My client code is the following :
Code:
#include <sys/types.h>#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#define MAX_COMANDO 10
char* juntarg(char *arg[])
{
char *frase=strdup(arg[1]);
strcat(frase," ");
return frase;
}
void ajuda()
{
printf("\n|------------------------- Ajuda ----------------------------------------|\n");
printf(" Para adicionar um ficheiro a monitorizar : \t ./cliente add \n");
printf(" Para mostrar os ficheiros que estão a ser monitorizados : ./cliente mostrar \n");
printf(" Para sair do programa : \t ./cliente exit\n");
printf("|------------------------------------------------------------------------|\n\n");
}
int main(int argc, char** argv) {
int pipe = open("trabfifo", O_WRONLY);
char *comando;
if(argc < 2) printf("Invocação do programa cliente mal realizada!\n");
else
{
if(strncmp(argv[1],"add",strlen(argv[1]))==0)
{
if(argc != 2) printf("O comando add foi mal invocado.\n Exemplo: ./cliente add n");
else
{
comando=juntarg(argv);
write(pipe,comando,strlen(comando));
}
}
else if(strncmp(argv[1],"mostrar",strlen(argv[1]))==0)
{
if(argc != 2) printf("O comando mostrar foi mal invocado.\n Exemplo: ./cliente mostrar n");
else
{
write(pipe,comando,strlen(comando));
}
}
else if(strncmp(argv[1],"help",strlen(argv[1])) == 0)
{
ajuda();
}
else printf("Comando Inexistente.\n");
return 1;
}
}"
And my server code is the following :
Code:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main(int argc, char** argv) {
int pipe;
char *comando;
pipe=mkfifo("trabfifo",0646);
open("trabfifo",O_RDONLY);
read(pipe,comando,strlen(comando)-1);
printf("%s \n",comando);
//close the pipe
close(pipe);
return 1;
}"
Any idea why it ain't working ?
Thanks a lot.
-
One thing I noticed is that commando is just an uninitialized pointer, so it does not make sense to read to it or use strlen on it.
-
How am I supposed to read it through the pipe then ? :o
-
? You read from your file descriptor called pipe, into memory at "comando", you read strlen(comando) -1 bytes.
Now look at comando, it's just a pointer, it does not reference any memory you own. Using strlen on it is completely unpredictable because commando does not point to a string.