我正在尝试使用管道从父进程内部使用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);
}
这可以编译,但我没有得到任何输出。有人可以帮忙吗?