在linux中,管道也是一种文件,只不过比较特殊,我们可以用pipe函数创建一个管道,其原型声明如下:
#inlcude
int pipe(int fields[2]);
其实它相当于一个通信缓冲区,fields[0]用来读,fields[1]用来写。下面的例子中,创建一个管道作为通信缓冲区,父进程创建了一个子进程,子进程通过管道的fields[1]描述符想管道中写入一个字符串,而父进程则利用管道的fields[0] 从管道中读取这个字串并显示出来:
#include
#include
#include
#include
#include
#include
#include
#define BUF_SIZ 255 // message buffer size
int main(int argc, char **argv)
{
char buffer[BUF_SIZ + 1];
int fd[2];
// receive a string as parameter
if ( argc != 2)
{
fprintf(stderr, "Usage: %s string\n\a", argv[0]);
exit(1);
}
// create pipe for communication
if ( pipe(fd) != 0 )
{
fprintf(stderr, "Create pipe error: %s\n\a", strerror(errno));
exit(1);
}
if ( fork() == 0 ) // in child process write msg to pipe
{
close(fd[0]);
printf("Child %ld write to pipe\n\a", getpid());
snprintf(buffer, BUF_SIZ, "%s", argv[1]);
write(fd[1], buffer, strlen(buffer));
printf("Child %ld quit.\n\a", getpid());
}
else // in parent process, read msg from pipe
{
close(fd[1]);
printf("Parent %ld read from pipe\n\a", getpid());
memset(buffer, '\0', BUF_SIZ + 1);
read(fd[0], buffer, BUF_SIZ);
printf("Parent %ld read : \n%s\n", getpid(), buffer);
exit(1);
}
return 0;
}
阅读(2523) | 评论(0) | 转发(0) |