Issue
I'm trying use pipes to write a string using write() from inside the parent process.And then spawn a child process wherein i read it,count the number of words and write the word count back.Then have the parent process print the word count. I've come up with this:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include<sys/wait.h>
int main(void)
{
int fd[2], nbytes,status,i,count=0;
pid_t PID;
char string[] = "Hello, world\n";
char readbuffer[80];
pipe(fd);
close(fd[0]);
write(fd[1], string, (strlen(string)+1));
if((PID=fork())<0)
{
printf("Error\n");
_exit(0);
}
else if(PID==0)
{
close(fd[1]);
nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
for(i=0;readbuffer[i]!='\0';i++)
{
if(readbuffer[i]==' ')
count++;
}
//open(fd[1]);
close(fd[0]);
write(fd[1],&count,1);
printf("The word count is %d ",count);
//open(fd[0]);
}
else
{
wait(&status);
if(WIFEXITED(status))
{
close(fd[1]);
nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("The word count is %d ",nbytes);
//open(fd[1]);
}
else
{
printf("Error\n");
_exit(0);
}
}
return(0);
}
This compiles but i don't get any output. Can someone please help?
Solution
I can't try the code but it looks like you are closing both the pipe ends in the child process. You use fd[1] to write but it is closed (before doing read).
I have no chance to compile and try this code so take it as an example and possibly fix problems. This example shows how to use two unidirectional pipes for sending data from the parent to the child process and from the child to the parent process.
int main(void)
{
int fd1[2], fd2[2], nbytes;
pid_t childpid;
char string[] = "Hello, world!\n";
char readbuffer[80];
pipe(fd1);
pipe(fd2);
if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}
if(childpid == 0)
{
/* Child process closes up input side of pipe fd1 */
close(fd1[0]);
/* Child process closes up output side of pipe fd2 */
close(fd2[1]);
/* Send "string" through the output side of pipe */
write(fd1[1], string, (strlen(string)+1));
/* Read in a string from the pipe */
nbytes = read(fd2[0], readbuffer, sizeof(readbuffer));
printf("Received string: %s", readbuffer);
exit(0);
}
else
{
/* Parent process closes up output side of pipe fd1 */
close(fd1[1]);
/* Parent process closes up input side of pipe fd2 */
close(fd2[0]);
/* Read in a string from the pipe */
nbytes = read(fd1[0], readbuffer, sizeof(readbuffer));
printf("Received string: %s", readbuffer);
/* Send "string" through the output side of pipe */
write(fd2[1], string, (strlen(string)+1));
}
return(0);
}
Answered By - Salvatore