我的问题很简单直接。这里我试图发送一个数据在pipe的一端,并试图从另一端读取。我试图学习IPC机制,并且在执行这个简单的程序时卡住了。如果我使用打印()[1]在父进程然后,为什么在使用管道的情况下,输出使用write()而不使用print()打印两次?
o/p is
In the child process
IN the parent process and its sleeping
SUBI IS IN LOVE WITH PUTHALATH
但是,如果我使用写()[2在下面的程序评价]在父进程
o/p is
In the child process
IN the parent process and its sleeping
SUBI IS IN LOVE WITH PUTHALATHIN the parent process and its sleeping
为什么“在父进程及其睡眠中”一行打印了两次?
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
int main(){
int fd[2];
pipe(fd);
if(!fork()){
printf("In the child process\n");
close(1);
dup(fd[1]);
close(fd[0]);
write(1,"SUBI IS IN LOVE WITH PUTHALATH", 200);
} else {
sleep(1);
printf("IN the parent process and its sleeping \n");
char* stream;
close(fd[1]);
read(fd[0],stream,200);
printf("%s",stream);------>(1)
// write(1,stream,200);---->(2)
}
return 0;
}
任何帮助请因为我卡在这里。
注意:你没有为'stream'分配内存。因此'read'是未定义的行为。 – 2013-03-12 19:06:32
'流'的名字很混乱。把它叫做buf并声明它是char buf [256];' – 2013-03-12 19:35:10