-------------------------
#include
#include
#include
#include
#include
#define oops(ch) {perror(ch);return -1;}
int main()
{
pid_t pid;
int filedes[2];
static int status;
char buf[20],buf1[10];
if(pipe(filedes)<0)
oops("pope");
if((pid=fork())<0)
oops("fork");
if(pid==0)
{
//sleep(5);
close(filedes[1]);
if(read(filedes[0],buf1,20)<0)
oops("read");
printf("the parent process write:%s\n",buf1);
exit(1);
}
else if(pid>0)
{
sleep(4);
close(filedes[0]);
if(read(STDIN_FILENO,buf,20)<0)
oops("read");
if(write(filedes[1],buf,20)==-1)
oops("write");
}
wait(&status);
exit(1);
}
----------------------------------------
结果
----------------------
[root@localhost pipe0420]# ./a*
fsf
the parent process write:fsf
����5�]
我想问下 为什么结果的最后一行会有些乱码!?
还有在gdb的时候为什么只有在read的时候才能进入子进程!?
谢谢!
suowenair 于 2010-04-22 13:14:41发表:
2# deepwhite
谢谢!
deepwhite 于 2010-04-21 13:32:56发表:
char buf[20],buf1[10];
没有初始化。
声明buff之后初始化就好了:
memset(buf, 0, 20);
memset(buf1, 0, 10);