Hey guys, I had to make some changes and how come this always returns 0 characters if I do like this in the parent:
[C] #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/ - Pastebin.com
Printable View
Hey guys, I had to make some changes and how come this always returns 0 characters if I do like this in the parent:
[C] #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/ - Pastebin.com
Please post the code on this site, not some link.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
main(int argc, char* argv[])
{
int fds[2], pid, i, fd;
char *pipeBuffer;
fd = open(argv[1], O_RDWR | O_APPEND);
if(argc != 2)
{
printf("Usage: my_program <filname of textfile>\n");
exit(0);
}
//create a pipe
if(pipe(fds) == -1)
{
perror("pipe");
exit(EXIT_FAILURE);
}
//create a fork
if((pid = fork()) == -1)
{
perror("fork");
exit(EXIT_FAILURE);
}
if(pid == 0)
{
close(fds[1]);
int letterCounter = 0;
int counter = 0;
printf("\n");
//read letters from the pipe
while(read(fds[0], &pipeBuffer[counter], 1) > 0)
{
if(isalpha(pipeBuffer[counter]))
{
letterCounter++;
}
counter++;
}
//write number of letters to end of file
char tmp[1]={0x0};
sprintf(tmp,"%d", letterCounter);
write(fd, tmp, strlen(tmp));
printf("Letters: %d\n\n", letterCounter);
close(fd);
close(fds[0]);
_exit(EXIT_SUCCESS);
}
else
{
close(fds[0]);
int c;
FILE *fdx, *fdy;
fdx = fdopen(fd, "r");
fdy = fdopen(fds[1], "w");
while((c = fgetc(fdx)) != EOF)
{
printf("%c", c);
fputc(c, fdy);
}
printf("\n\n");
fclose(fdx);
fclose(fdy);
close(fds[1]);
wait(NULL);
exit(EXIT_SUCCESS);
}
}
Compiling with warnings I get:
Code:$ make foo
cc -Wall -Wextra -ggdb3 foo.c -o foo
foo.c:11:1: warning: return type defaults to ‘int’ [-Wreturn-type]
foo.c: In function ‘main’:
foo.c:51:7: warning: implicit declaration of function ‘isalpha’ [-Wimplicit-function-declaration]
foo.c:13:20: warning: unused variable ‘i’ [-Wunused-variable]
foo.c:51:28: warning: ‘pipeBuffer’ may be used uninitialized in this function [-Wuninitialized]
"pipeBuffer" points to anywhere. And indexing it will likely result in a crash with a bigger file.Code:char *pipeBuffer;
...
while(read(fds[0], &pipeBuffer[counter], 1) > 0)
But since you just want to read one character after another you don't need to use a buffer. Just do
Code:char c;
read(fds[0], &c, 1);
Here's another buffer overrun:
How many characters can you store in "tmp"?Code:char tmp[1]={0x0};
sprintf(tmp,"%d", letterCounter);
Bye, Andreas