通道
匿名通道
#include <unistd.h>
int pipe(int pipefd[2]);
作为进程间共享区,只用于通信,通信结束后就自动移除。它是一个单向的数据传输通道,参数第一个值为读取的文件描述符(对应输入),第二个值为写入的文件描述符(对应输出)
它只能用于拥有公共祖先进程的进程(也就是必须继承同一个文件描述符表,保证它们的文件描述符必须指向同一文件)
下面是匿名通道的实现
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char const *argv[]) {
//创建管道
int fd[2];
if (pipe(fd) == -1) {
perror("pipe faild");
}
//创建进程
pid_t pid = fork();
if (pid == -1) {
perror("fork faild");
}
if (!pid) { //子进程
char *s = (char *)malloc(sizeof(char) * 100);
strcpy(s, "hello, ACM!");
//关掉读取
close(fd[0]);
//写入
write(fd[1], s, strlen(s) + 1);
} else { //父进程
char buffer[100];
//关掉写入
close(fd[1]);
//读取
read(fd[0], buffer, sizeof(buffer));
printf("%s\n", buffer);
}
return 0;
}
命名管道
#include <sys/types.h>
#include <sys/stat.h>
//创建命名管道,它采取先进先出的策略
int mkfifo(const char* pathname, mode_t mode);
//访问命名管道
参数一为文件路径,参数二表示这个命名管道的权限可被umask修改
命名管道可以任意进程间进行通信,且创建它的进程退出后它仍然存在,只有在被删除后才消失。它不同于一般文件在于读取和写入数据的进程必须同时出现(也就是说只有读或写,命名管道就会被阻塞)
如果有写的不对或者不全面的地方 可通过主页的联系方式进行指正,谢谢