I am trying to send two messages from the parent to the receiver. Only one is received. Receiver uses stdin and stdout for the pipe, and outputs its results into std err. Here is my code.
#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;
}
答案 0 :(得分:3)
问题是strlen(arr)+1
部分。您还发送了终止符nul
,而nul
最终构成了scanf
读取的第二个“字符串”:
REC: HelloWorld
REC:
如果您删除了+1
,则会得到两行提示(我还减少了睡眠时间,因为我没有耐心等待50秒以获得结果):
#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(2);
}
else
{
close(pipes[0]);
// Read in a string from the pipe
char* arr = "HelloWorld\n";
write(pipes[1],arr,strlen(arr)); // << NO +1
write(pipes[1],arr,strlen(arr)); // << NO +1
sleep(2);
}
return 0;
}
答案 1 :(得分:0)
以下行是一个问题:
scanf("%s\n",buffer);
除非有指令匹配,否则 scanf
不会读取结尾的空格(包括换行符)。但是指令存在于此。因此,它会在输入之后的常规新行之后等待另一新行。
删除两个\n
语句中的scanf
。
第二,您必须修改fprintf
语句以在其中添加\n
。
fprintf(stderr,"REC: %s\n",buffer);
第三,不要在strlen(arr)
中的write
上加1。修改为:
write(pipes[1],arr,strlen(arr));
有效。参见live demo:
输出:
REC: HelloWorld
REC: HelloWorld
Real time: 2.082 s
User time: 0.043 s
Sys. time: 0.037 s
CPU share: 3.85 %
Exit code: 0