1、匿名管道、父子间进程通信
#include<unistd.h>
#include<errno.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int pipe_fd[2];
if (pipe(pipe_fd) < 0)
{
printf("pipe create error \n");
return - 1;
}
printf("pipe create success\n");
if (fork() > 0)
{
int r;
char buf[15 + 1];
printf("Want to read from son \n");
r = read(pipe_fd[0], buf, 15);
buf[r] = 0;
printf("Father Got strings: %s \n", buf);
}
else
{
const char* test = "I am your name";
printf("Son sleep:\n");
sleep(5);
printf("SonWrite after sleep: %s \n", test);
write(pipe_fd[1], test, strlen(test));
}
close(pipe_fd[0]);
close(pipe_fd[1]);
return 0;
}
分析:
父进程通过pipe()调用申请创建第三方缓冲区并获得了该内存区域的读写端地址,在调用fork后,会将读写的端地址复制给子进程。父子进程产生后,子进程执行向管道写入数据,父进程从管道读出数据,从而完成一次父子进程的通信。
在子进程中加入了sleep语句,所以子进程的执行会产生休眠,从而向管道写入数据要需要等待。此时父进程由于没有从管道中获得数据,也会处于等待状态,等子进程启动后,管道才使得父子进程之间可以通信。
2、命名管道、非亲缘关系的进程通信
读进程
#include<errno.h>
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
int main(int argc, char* argv[])
{
if (argc != 2)
{
printf("not enough params,give pipefile name \n");
exit(1);
}
char* pipefile;
pipefile = argv[1];
char buf[100];
int fd, i;
printf("read open namedpipe \n");
fd = open(pipefile, O_RDONLY, 0);
if (fd < 0)
{
printf("no such namedpipe file \n");
exit(-1);
}
printf("OK,namedpipe opened for read \n");
i = read(fd, buf, 100);
buf[i] = 0;
printf("OK,readed from namedpipe: %s \n", buf);
return 0;
}
写进程
#include<errno.h>
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
int main(int argc, char* argv[])
{
if (argc != 2)
{
printf("not enough params,give pipefile name \n");
exit(1);
}
char* pipefile;
pipefile = argv[1];
char buf[100];
int fd;
char* teststr = "I am your name \n";
printf("OPEN namedpipe -- %s for write \n", pipefile);
fd = open(pipefile, O_WRONLY, 0);
printf("OK,namedpipe -- %s opened for write \n", pipefile);
sleep(5);
write(fd, teststr, strlen(teststr));
printf("OK,namedpipe write successfully \n");
exit(0);
return 0;
}
分析:
首先进行读进程,刚开始读就产生了阻塞,因为管道的规则需要两方同时存在的时候才可以向下访问,写端还没有执行,所以读端阻塞了。
执行写入端,开始执行后由于存在sleep语句睡眠5秒,等5秒结束后管道两边同时存在读写进程,两个无亲缘关系的进程直接完成了一次通信。