在 C 中使用管道发送字符
Sending characters using pipes in C
我正在尝试使用 C 编程语言中的管道将 string 从父进程发送到子进程,它几乎可以正常工作,但是我收到没有第一个字符的不完整字符串。我的代码有什么问题?谢谢你。
#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;
}
问题是您首先读取 1 个字节以查看它是否不是 nul 终止符,但随后该信息消失了,因为您在后面的调用中覆盖了它!所以你需要在后面的调用中增加指针。
if(!read(p[0],&inputBuffer,1))
{
close(p[0]);
break;
}
else
{
char *pointer = &inputBuffer;
read(p[0],pointer+1,99);
}
我正在尝试使用 C 编程语言中的管道将 string 从父进程发送到子进程,它几乎可以正常工作,但是我收到没有第一个字符的不完整字符串。我的代码有什么问题?谢谢你。
#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;
}
问题是您首先读取 1 个字节以查看它是否不是 nul 终止符,但随后该信息消失了,因为您在后面的调用中覆盖了它!所以你需要在后面的调用中增加指针。
if(!read(p[0],&inputBuffer,1))
{
close(p[0]);
break;
}
else
{
char *pointer = &inputBuffer;
read(p[0],pointer+1,99);
}