管线是哪些?
管线是Linux系统一下一种IPC通讯机制,可以用于进程间通讯,线程间通讯。
用管线进行通讯的时侯主要由如下两种局限性:
管线是半双工的,及数据只能在一个方向上流动;管线只能在具有公共先祖的两个进程之间使用。一般一个管线由一个进程创建,在进程调用fork以后,这个管线能够在父进程和子进程之间使用了。管线的创建
linux系统下管线通过pipe函数创建
#include
int pipe(int fd[2]);
由参数字段fd返回两个文件描述符:
fd[0]用于读数据;fd[1]用于写数据;
如右图所示半双工,数据只能在一个方向下面流动,管线fd[0]和fd[1]都在同一个进程使用。
在多进程通讯的过程中什么是linux,一般都是在父进程先调用pipe,创建管线,之后fork子进程,因而创建父进程到子进程的通道。
fork以后做哪些取决于我们须要的数据流方向
当管线一端被关掉后,有如下两条规则适用
1)读取一个写端早已被关掉的管线是,在所有的数据都被读取后,read返回0.表示文件以及结束。
2)假如写一个读端早已关掉的关掉,则形成讯号SIGPIPE。假如忽视该讯号或则捕捉该讯号并从其处理程序返回linux使用教程,则write返回-1linux 管道文件linux 管道文件,errno设置为EPIPE。
下边通过一个示例程序演示子进程到父进程的数据流:
#include
#include
#include
#include
#include
int main()
{
int ret = -1;
int fd[2];
pid_t pid;
char buf[512] = {0};
char *msg = "child say:hello world";
//create pipe
ret = pipe(fd);
if (-1 == ret) {
printf("failed to create pipen");
return -1;
}
pid = fork();
if (-1 == pid) {
printf("failed forkn");
return -1;
}
if (0 == pid) {
printf("child process...n");
close(fd[0]);
ret = write(fd[1], msg, strlen(msg));
printf("child send %d byte char to parentn", ret);
close(fd[1]);
exit(0);
}
else {
close(fd[1]);
ret = read(fd[0], buf, sizeof(buf));
close(fd[0]);
printf("parent read %d bytes data:%sn", ret, buf);
}
return 0;
}
编译代码
[root@localhost pipe]# gcc -g pipe.cc -o pipetest
运行代码
[root@localhost pipe]# ./pipetest
child process...
child send 21 byte char to parent
parent read 21 bytes data:child say:hello world