無名管道系統調用
#include
#include
#include
#include
#include
#include
#define MAX 256
#define DELAY 1
int main()
{
pid_t pid;
int pipe_fd[2]; //定義兩個文件描述符
char buf[MAX]; //定義緩衝區大小
const char data[] = "Pipe Test Program"; //定義數據
int real_read,real_write;
memset((void*)buf,0,sizeof(buf)); //清空內存區
if(pipe(pipe_fd) < 0) //創建管道
{
printf("pipe create error/n");
exit(1);
}
if((pid = fork()) == 0) //創建一子進程
{//子進程關閉寫描述符,並通過子進程暫停1s等待父進程已關閉相應的讀描述符
close(pipe_fd[1]);
sleep(DELAY * 3);
if((real_read = read(pipe_fd[0],buf,MAX)) > 0) //子進程讀取管道內容
{
printf("%d bytes read from the pipe is '%s'/n",real_read,buf); }
close(pipe_fd[0]); //關閉子進程讀描述符
exit(0);
}
else if(pid > 0)
{//父進程關閉讀描述符,並通過使使父進程暫停1s等待子進程已關閉相應的寫描述符
close(pipe_fd[0]);
sleep(DELAY);
if((real_write = write(pipe_fd[1],data,strlen(data))) != -1) //父進程寫入管道內容
{
printf("Parent wrote %d bytes:'%s'/n",real_write,data);
}
close(pipe_fd[1]); //關閉父進程寫描述符
waitpid(pid,NULL,0); //收集子進程退出信息
exit(0);
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.