H5網(wǎng)站建設(shè)報(bào)價(jià)多少網(wǎng)絡(luò)營(yíng)銷(xiāo)推廣系統(tǒng)
父子進(jìn)程:
父子進(jìn)程的變量之間存在著讀時(shí)共享,寫(xiě)時(shí)復(fù)制原則
無(wú)名管道:
無(wú)名管道僅能用于有親緣關(guān)系的進(jìn)程之間通信如父子進(jìn)程
代碼:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/fcntl.h>
#include <stdlib.h>#define N 100int main(int argc, const char *argv[]){pid_t pid;int fdr, fdw;ssize_t nbyte;int fd[2];char buf[N] = "";if(argc != 1 && argc != 3){printf("number error\n");exit(0);}if((fdr = open(argv[1], O_RDONLY)) < 0){printf("read open error\n");exit(0);}if((fdw = open(argv[2], O_CREAT|O_WRONLY|O_TRUNC, 0664)) < 0){printf("write open error\n");exit(0);}if(pipe(fd) < 0){printf("pipe error\n");exit(0);}pid = fork();//創(chuàng)建子進(jìn)程if(pid < 0){printf("fork error\n");exit(0);}else if(pid == 0){ // 子進(jìn)程 while((nbyte = read(fd[0], buf, N)) > 0){ // 管道讀取端讀取消息 write(fdw, buf, nbyte); // 寫(xiě)入文件 } }else{while((nbyte = read(fdr, buf, N)) > 0){ // 在被讀寫(xiě)的文件中讀取數(shù)據(jù) write(fd[1], buf, nbyte); // 在管道寫(xiě)入端寫(xiě)入數(shù)據(jù) }}return 0;
}
解釋:
父進(jìn)程打開(kāi)并讀取讀文件中的數(shù)據(jù),并將數(shù)據(jù)放入無(wú)名管道的寫(xiě)入端,子進(jìn)程從無(wú)名管道的讀取端讀取數(shù)據(jù)并寫(xiě)入自己事先打開(kāi)或創(chuàng)建的接受文件,直到管道內(nèi)沒(méi)有數(shù)據(jù),最終文件實(shí)現(xiàn)復(fù)制效果。
注意:read函數(shù)返還值為真實(shí)讀取的數(shù)據(jù),N為讀取的數(shù)據(jù)