我正在尝试使用 C 编程语言中的管道将字符串从父进程发送到子进程,它几乎正常工作,但是我收到不完整的字符串而没有第一个字符。我的代码错了什么?谢谢。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
int main(int argc, char** args)
{
int pid, p[2];
int status = -100;
char input[100];
char inputBuffer[100];
if(pipe(p) == -1)
{
return -1;
}
if((pid = fork())<0)
{
printf("error\n");
}
else
{
if(pid==0)
{
close(p[1]);
while(1)
{
if(!read(p[0],&inputBuffer,1))
{
close(p[0]);
break;
}
else
{
read(p[0],&inputBuffer,100);
}
}
printf("received: %s\n",inputBuffer);
exit(0);
}
else
{
printf("Enter String\n");
scanf("%s", &input);
printf("String Entered: %s\n",input);
close(p[0]);
write(p[1], input, strlen(input)+1);
close(p[1]);
wait(&status);
}
}
return 0;
}
答案 0 :(得分:1)
问题是您首先读取1个字节以查看它是否是一个无终止符,但随后该信息消失了,因为您在后一个调用中覆盖了它!所以你需要增加后一个调用的指针。
if(!read(p[0],&inputBuffer,1))
{
close(p[0]);
break;
}
else
{
char *pointer = &inputBuffer;
read(p[0],pointer+1,99);
}