[英]why cannot the parent read from child
在這里,我遇到了有關管道的問題。
如果我在父級中寫入管道,而在子級中讀取管道,則如下所示:
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);
}
}
另一種方法是:
// Parent writes, child reads and prints
if(pid != 0)
{
char str[] = "hello!";
close(mypipe[0]);
write(mypipe[1], str, strlen(str)+1);
while(wait(&state) != pid); // ensure child has read the pipe
close(mypipe[1]); // now we can close it
exit(0);
}
else
{
char str1[100];
close(mypipe[1]);
read(mypipe[0], str1, 100);
close(mypipe[0]);
printf("pipe: %s\n", str1);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.