/*
主進程創(chuàng)建2個子進程,子進程1每隔1秒向子進程2發(fā)送一個
字符串,子進程接收到該字符串之后將其寫入一個指定的文件
*/
#include
#include
#include
#include
#include
#include
#include
#include
//以下為主函數(shù)
int main(int argc,char *argv[])
{
pid_t pid1,pid2; //進程的ID
int fd; //文件描述符
char writebuf[] = "this is a test!\n"; //待寫入字符串
char readbuf[25]; //讀緩沖區(qū)
int writecounter = 0; //用于記錄寫入的偏移量
int temp = 0,seektemp = 0,j = 0; //都是用于計算文件偏移的臨時變量
int pipefd[2]; //管道的文件描述符
if (argc != 2) //如果參數(shù)不正確
{
printf("請輸入正確的文件參數(shù)。\n");
return 0;
}
fd = open(*(argv+1),O_RDWR|O_CREAT,S_IRWXU); //打開或者創(chuàng)建一個文件
if(pipe(pipefd) < 0) //如果創(chuàng)建管道失敗
{
printf("創(chuàng)建管道失敗。\n");
exit(0); //退出
}
pid1 = fork(); //調(diào)用fork創(chuàng)建一個新的進程
if(pid1 != 0) //主進程
{
pid2 = fork(); //創(chuàng)建第二個子進程
if(pid2 != 0) //主進程
{
close(pipefd[0]); //關(guān)閉管道
close(pipefd[1]);
}
else //這是子進程2的操作
{
close(pipefd[1]);
while(1)
{
read(pipefd[0],readbuf,sizeof(writebuf)); //讀管道
printf("這是子進程2.\n"); //屏幕輸出提示
if(writecounter == 0) //第一次寫入
{
temp = write(fd,readbuf,strlen(readbuf)); //寫入數(shù)據(jù)
seektemp = lseek(fd,0,SEEK_CUR); //獲得當前偏移量
writecounter++;
}
else
{
j = strlen(readbuf)*writecounter;
seektemp = lseek(fd,j,SEEK_SET);
temp = write(fd,readbuf,strlen(writebuf));
writecounter++;
}
}
}
}
else //子進程
{
close(pipefd[0]);
while(1)
{
sleep(1);
write(pipefd[1],writebuf,sizeof(writebuf)); //將字符串寫入管道
}
}
}
本文題目:[Linux管道和IPC]管道的實際應用1
網(wǎng)頁URL:
http://weahome.cn/article/ppohie.html