パイプを使用して、親プロセス内からwrite()を使用して文字列を書き込もうとしています。次に、子プロセスを生成して、それを読み取り、単語数を数え、単語数を書き戻します。次に、親プロセスに単語数。私はこれを思いついた:
#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);
}
これはコンパイルされますが、出力が得られません。誰か助けてくれませんか?