当前位置: 技术问答>linux和unix
管道都关了,他还怎么共享呀?
来源: 互联网 发布时间:2015-12-10
本文导语: #include #include #include intmain(void) { intfd[2],nbytes; pid_tchildpid; charstring[]="Hello,world!n"; charreadbuffer[80]; pipe(fd); if((childpid=fork())==-1) { perror("fork"); exit(1); } if(childpid==0) { /*Child process closes up in put side of pipe*/ close(fd[0]); //子...
#include
#include
#include
intmain(void)
{
intfd[2],nbytes;
pid_tchildpid;
charstring[]="Hello,world!n";
charreadbuffer[80];
pipe(fd);
if((childpid=fork())==-1)
{
perror("fork");
exit(1);
}
if(childpid==0)
{
/*Child process closes up in put side of pipe*/
close(fd[0]); //子进程把fd[0]都关了,父进程还怎么从fd[0]读数据呢?
/*Send"string"through the out put side of pipe*/
write(fd[1],string,strlen(string));
exit(0);
}
else
{
/*Parent process closes up out put side of pipe*/
close(fd[1]);
/*Readinastringfromthepipe*/
nbytes=read(fd[0],readbuffer,sizeof(readbuffer));
printf("Receivedstring:%s",readbuffer);
}
return(0);
}
子进程把fd[0]都关了,父进程还怎么从fd[0]读数据呢?
#include
#include
intmain(void)
{
intfd[2],nbytes;
pid_tchildpid;
charstring[]="Hello,world!n";
charreadbuffer[80];
pipe(fd);
if((childpid=fork())==-1)
{
perror("fork");
exit(1);
}
if(childpid==0)
{
/*Child process closes up in put side of pipe*/
close(fd[0]); //子进程把fd[0]都关了,父进程还怎么从fd[0]读数据呢?
/*Send"string"through the out put side of pipe*/
write(fd[1],string,strlen(string));
exit(0);
}
else
{
/*Parent process closes up out put side of pipe*/
close(fd[1]);
/*Readinastringfromthepipe*/
nbytes=read(fd[0],readbuffer,sizeof(readbuffer));
printf("Receivedstring:%s",readbuffer);
}
return(0);
}
子进程把fd[0]都关了,父进程还怎么从fd[0]读数据呢?
|
刚看了一下内核情景分析,好象是这样的,PIPE之后进程的文件打开表中分别有了一个指向管道文件的读端与写端.
子进程在FORK之后在其打开文件表中也有了指向同一个管道文件的读端与写端
在你CLOSE父进程的写端后与子进程的读端后,子进程就只能向管道文件中写,而父进程只能读出管道中子进程写的内容.
子进程在FORK之后在其打开文件表中也有了指向同一个管道文件的读端与写端
在你CLOSE父进程的写端后与子进程的读端后,子进程就只能向管道文件中写,而父进程只能读出管道中子进程写的内容.