管道读写
管道主要用于不同進程間通信。
通常先創建管道,再通過fork()函數創建一個子進程。
子進程寫入和父進程讀的命名管道。
管道讀寫注意事項:
可以通過打開的兩個管道來創建一個雙向的管道。
但需要在子正確的設置文件描述符。
必須在系統調用fork()中調用 pipo()
否則子進程將不會繼承文件描述符。
當使用半雙工管道時,任何關聯的進程都必須共享一個相關的祖先進程。
因為管道存在于系統內核之中。所以任何不在創建管道的進程的祖先進程之中的進程都無法尋址它。而在命名管道中卻不是這樣的。
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));//數組的數據清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
總結
- 上一篇: 链表反转的两种实现方法
- 下一篇: 流管道