C 为什么父对象不能从子对象读取数据
这里我遇到了一个关于管道的问题 如果我在父对象中写入管道并在子对象中读取管道,如下所示:C 为什么父对象不能从子对象读取数据,c,unix,pipe,C,Unix,Pipe,这里我遇到了一个关于管道的问题 如果我在父对象中写入管道并在子对象中读取管道,如下所示: if(pid == 0){ char str1[100]; close(mypipe[1]); read(mypipe[0], str1, 6); close(mypipe[0]); exit(0); } else{ while(wait(&state) != pid); char str[] = "hello!"; close(myp
if(pid == 0){
char str1[100];
close(mypipe[1]);
read(mypipe[0], str1, 6);
close(mypipe[0]);
exit(0);
}
else{
while(wait(&state) != pid);
char str[] = "hello!";
close(mypipe[0]);
write(mypipe[1], str, strlen(str)+1);
close(mypipe[1]);
printf("pipe: %s\n", str);
}
if(pid == 0){
char str[] = "hello!";
close(mypipe[0]);
write(mypipe[1], str, strlen(str)+1);
close(mypipe[1]);
exit(0);
}
else{
while(wait(&state) != pid);
char str1[100];
close(mypipe[1]);
read(mypipe[0], str1, 6);
close(mypipe[0]);
printf("pipe: %s\n", str);
}
然后我就可以拿到指纹了喂
但如果我在child中写,在parent中读,就像这样:
if(pid == 0){
char str1[100];
close(mypipe[1]);
read(mypipe[0], str1, 6);
close(mypipe[0]);
exit(0);
}
else{
while(wait(&state) != pid);
char str[] = "hello!";
close(mypipe[0]);
write(mypipe[1], str, strlen(str)+1);
close(mypipe[1]);
printf("pipe: %s\n", str);
}
if(pid == 0){
char str[] = "hello!";
close(mypipe[0]);
write(mypipe[1], str, strlen(str)+1);
close(mypipe[1]);
exit(0);
}
else{
while(wait(&state) != pid);
char str1[100];
close(mypipe[1]);
read(mypipe[0], str1, 6);
close(mypipe[0]);
printf("pipe: %s\n", str);
}
然后它什么也不打印
我真的不知道为什么…虽然第二个示例代码中有错误,但str没有在该范围内定义,而且很明显,Hello!在您的第一个示例代码中打印,因为您刚刚用该内容定义了一个字符串并打印了它,而您声称不起作用的第二个代码实际上起作用了:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main()
{
int mypipe[2];
int pid, state;
pipe(mypipe);
pid = fork();
// Child writes, parent reads and prints
if(pid == 0)
{
char str[] = "hello!";
close(mypipe[0]);
write(mypipe[1], str, strlen(str)+1);
close(mypipe[1]);
exit(0);
}
else
{
char str1[100];
while(wait(&state) != pid);
close(mypipe[1]);
read(mypipe[0], str1, 100); // you should read at least 7 bytes, not 6,
// in order to receive the trailing \0 byte.
close(mypipe[0]);
printf("pipe: %s\n", str1);
}
}
在第一个示例中,读取端没有打印任何内容,因此您无法知道读取端是否实际收到了某些内容。ptintf位于写端。此外,第二个示例包含一个错误:str未在此范围内定义,但str1未定义的“str”在编辑时是错误的。现在代码在Ubuntu上正确运行,但在UnixV6上仍然不打印任何内容。UNIX V6的系统函数“pipe”可能有问题。非常感谢你!一些管道实现具有一端只读和一端写只读。检查write调用的返回值,如果其中一个调用失败,请使用perror发出错误消息。这可能会告诉你出了什么问题。