【发布时间】:2013-03-12 18:57:15
【问题描述】:
我的问题很简单直接。在这里我试图在管道的一端发送数据并尝试从另一端读取。我正在尝试学习 IPC 机制,但在执行这个简单的程序时遇到了困难.如果我在父进程中使用 print()[1] 那么,
o/p is
In the child process
IN the parent process and its sleeping
SUBI IS IN LOVE WITH PUTHALATH
但是如果我在父进程中使用 write()[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
为什么会打印两次“IN the parent process and its sleep”行?
#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是未定义的行为。 -
stream的名称令人困惑。称它为buf并声明它为char buf[256];