【发布时间】:2019-02-23 08:47:09
【问题描述】:
我正在尝试从父母向接收者发送两条消息。只收到一个。 Receiver 使用 stdin 和 stdout 作为管道,并将其结果输出到 std err。这是我的代码。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
int main(int argc,char * argv[])
{
char buffer[100]; // The pipe's buffer
int pipes[2];
pid_t childpid;
if ( pipe(pipes) ){
fprintf(stderr,"FATAL ERROR IN PIPE");
}
if((childpid = fork()) == -1){
perror("fork");
exit(1);
}
if(childpid == 0){
close(pipes[1]);
dup2(pipes[0],STDIN_FILENO);
scanf("%s\n",buffer);
fprintf(stderr,"REC: %s\n",buffer);
scanf("%s\n",buffer);
fprintf(stderr,"REC: %s\n",buffer);
sleep(50);
}
else
{
close(pipes[0]);
// Read in a string from the pipe
char* arr = "HelloWorld\n";
write(pipes[1],arr,strlen(arr)+1);
write(pipes[1],arr,strlen(arr)+1);
sleep(50);
}
return 0;
}
【问题讨论】:
-
管道中没有消息,只有字节流。
-
没有消息是什么意思。我在父进程中发送了两次消息“HelloWorld\n”
-
建议从
scanf("%s\n",buffer);的格式中删除"\n"。你认为"\n"做了什么?可能是“只收到一个”的贡献者。 -
@Antoun 它的意思是“你似乎期望管道支持不同的消息,并且可以一次传递一个,但事实并非如此,管道只是字节”。至少这是我的解释。
-
那程序怎么知道这是消息的结尾呢?