进程间通信:无名管道
无名管道(pipe)是一种半双工的进程间通信方式,只能用于有公共祖先的进程间通信. 通常一个进程创建一个管道后,fork出一个子进程,然后子进程中也可以使用pipe了.
定义一个管道: int fpipe[2];// 其中fpipe[0]是读, fpipe[1]是写.
创建管道: int pipe(fpipe);
简单例子如下:
#include
include
include
define MAXLINE 20
int main(void )
{
char line[MAXLINE];
//define the pipe
int fpipe[2];
if(pipe(fpipe)<0)
{
printf(“error taken place during creating the pipe! \n”);
return 1;
}
pid_t pid;
if ((pid = fork())< 0)
{
printf(“error taken place during creating fork()! \n”);
return 1;
}
else if(pid == 0 )
{
//in the child’s process
close(fpipe[0]);
//only write;
write(fpipe[1], “I’m the data!”, MAXLINE);
}
else
{
//in the parent process
sleep(2);
close(fpipe[1]);
//read
read(fpipe[0], line, MAXLINE);
printf(“pipe: %s \n”, line);
}
return 0;
}
pipe用于进程间同步:
include
include
include
define MAXLINE 200
int main(void )
{
char line[MAXLINE];
//define the pipe
int fpipe[2];
if(pipe(fpipe)<0)
{
printf(“error taken place during creating the pipe! \n”);
return 1;
}
pid_t pid;
if ((pid = fork())< 0)
{
printf(“error taken place during creating fork()! \n”);
return 1;
}
else if(pid == 0 )
{
//in the child’s process
close(fpipe[0]);
//only write;
write(fpipe[1], “c”, 1);
}
else
{
//in the parent process
close(fpipe[1]);
//read
char t = 0;
read(fpipe[0], &t, 1);
if(t == ‘c’)
{
printf(“process synchronization done! \n”);
}
else
{
printf(“error taken place!”);
}
}
return 0;
}