X
Xarky
Hi,
I wrote the following program (source code below). I am using
pipes, were the parent reads and the child writes.
My problem is that I am writing the same line in the pipe for a
fixed number of times 50 (made a for loop). When writing it back it
to string I made a counter(cnt) to count the occurances of each
string. The problem is that never gives me 50, but 43.
Probably my problem is with the file descriptors.
Can some one help me pls.
Thanks in advance
/* Source code */
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#define MAX 20
main()
{
system ("clear");
pid_t pid;
int fd[2];
ssize_t data;
char buff[MAX];
char msg[] = "hello, world.\n\0";
if (pipe(fd) < 0) // creating pipe
printf ("Error encountered: %s.\n", strerror(errno));
else // no error encountered
{
if ((pid = fork()) == -1)
printf ("Error encountered: %s.\n", strerror(errno));
else if (pid == 0) // child to write
{
close (fd[0]); // closing reading part
int i;
for (i=0; i<500; i++)
write (fd[1], msg, sizeof(msg));
close (fd[1]); // terminating writing
_exit(0);
} // end child process
else // parent to read
{
close (fd[1]); // closing writing part
int cnt=0;
data = read (fd[0], buff, sizeof(buff)-1);
while (data != 0)
{
cnt++;
write (fileno(stdout), buff, data);
data = read (fd[0], buff, sizeof(buff)-1);
} // end loop
printf ("Number of strings counted is %d.\n", cnt);
close (fd[0]); // terminating reading
} // end parent process
} // end else
} // end main
I wrote the following program (source code below). I am using
pipes, were the parent reads and the child writes.
My problem is that I am writing the same line in the pipe for a
fixed number of times 50 (made a for loop). When writing it back it
to string I made a counter(cnt) to count the occurances of each
string. The problem is that never gives me 50, but 43.
Probably my problem is with the file descriptors.
Can some one help me pls.
Thanks in advance
/* Source code */
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#define MAX 20
main()
{
system ("clear");
pid_t pid;
int fd[2];
ssize_t data;
char buff[MAX];
char msg[] = "hello, world.\n\0";
if (pipe(fd) < 0) // creating pipe
printf ("Error encountered: %s.\n", strerror(errno));
else // no error encountered
{
if ((pid = fork()) == -1)
printf ("Error encountered: %s.\n", strerror(errno));
else if (pid == 0) // child to write
{
close (fd[0]); // closing reading part
int i;
for (i=0; i<500; i++)
write (fd[1], msg, sizeof(msg));
close (fd[1]); // terminating writing
_exit(0);
} // end child process
else // parent to read
{
close (fd[1]); // closing writing part
int cnt=0;
data = read (fd[0], buff, sizeof(buff)-1);
while (data != 0)
{
cnt++;
write (fileno(stdout), buff, data);
data = read (fd[0], buff, sizeof(buff)-1);
} // end loop
printf ("Number of strings counted is %d.\n", cnt);
close (fd[0]); // terminating reading
} // end parent process
} // end else
} // end main