管道读写
管道主要用于不同進(jìn)程間通信。
通常先創(chuàng)建管道,再通過fork()函數(shù)創(chuàng)建一個(gè)子進(jìn)程。
子進(jìn)程寫入和父進(jìn)程讀的命名管道。
管道讀寫注意事項(xiàng):
可以通過打開的兩個(gè)管道來創(chuàng)建一個(gè)雙向的管道。
但需要在子正確的設(shè)置文件描述符。
必須在系統(tǒng)調(diào)用fork()中調(diào)用 pipo()
否則子進(jìn)程將不會(huì)繼承文件描述符。
當(dāng)使用半雙工管道時(shí),任何關(guān)聯(lián)的進(jìn)程都必須共享一個(gè)相關(guān)的祖先進(jìn)程。
因?yàn)楣艿来嬖谟谙到y(tǒng)內(nèi)核之中。所以任何不在創(chuàng)建管道的進(jìn)程的祖先進(jìn)程之中的進(jìn)程都無法尋址它。而在命名管道中卻不是這樣的。
pipo_rw.c
#include <unistd.h>
#include <memory.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
? ? int pipe_fd[2];
? ? pid_t pid;
? ? char buf_r[100];
? ? int r_num;
? ? memset(buf_r, 0, sizeof(buf_r));//數(shù)組的數(shù)據(jù)清0
? ? if ((pipe(pipe_fd)) < 0)
? ? {
? ? ? ? printf("pipe create error\n");
? ? ? ? return -1;
? ? }
? ? if ((pid=fork())==0)
? ? {
? ? ? ? printf("\n");
? ? ? ? close(pipe_fd[1]);
? ? ? ? sleep(2);
? ? ? ? if (r_num=read(pipe_fd[0], buf_r, 100) > 0)
? ? ? ? {
? ? ? ? ? ? printf("%d numbers read from be pipe is %s\n", r_num, buf_r);
? ? ? ? }
? ? ? ? close(pipe_fd[0]);
? ? ? ? exit(0);
? ? }
? ? else if (pid > 0)
? ? {
? ? ? ? close(pipe_fd[0]);
? ? ? ? if (write(pipe_fd[1], "HELLO", 5) != -1)
? ? ? ? ? ? printf("parent write success!\n");
? ? ? ? if (write(pipe_fd[1], "PIPE", 5) != -1)
? ? ? ? ? ? printf("parent write success!\n");
? ? ? ? close(pipe_fd[1]);
? ? ? ? sleep(3);
? ? ? ? waitpid(pid, NULL, 0);
? ? ? ? exit(0);
? ? }
? ? return 0;
}
cc pipe_rw.c -o pipo_rw
./pipo_rw?
parent write success!
parent write success!
1 numbers read from be pipe is HELLOPIPE
總結(jié)
- 上一篇: 链表反转的两种实现方法
- 下一篇: 流管道