[技術] Linux管線(pipe)程式

Written on 8:07 下午 by Yu Lai

From: http://blog.csdn.net/lcrystal623/archive/2007/03/05/1521168.aspx

管線只能用於父子程序間通信,pipe函式用一個int[]作參數,int[] fd中fd[0]用於讀,fd[1]用於寫。代碼如下:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>

int main()
{
int pipe1_fd[2], pipe2_fd[2];

char * parent_talks[] = {"Hi, my baby","Can you tell daddy date and time?","Daddy have to leave here, bye!",NULL};
char * child_talks[] = {"Hi, daddy","Sure,","Bye!",NULL};

char parent_buf[256], child_buf[256];
char * parent_ptr, * child_ptr;

int i,j, len;
int child_status;
time_t curtime;

if(pipe(pipe1_fd) < 0)
{
printf("pipe1 create error\n");
return -1;
}

if(pipe(pipe2_fd) < 0)
{
printf("pipe2 create error\n");
return -1;
}

if(fork() == 0) //child
{
//pipe1_fd[0] is used to read, pipe2_fd[1] is used to write
close(pipe1_fd[1]);
close(pipe2_fd[0]);

i = 0;
child_ptr = child_talks[i];
while(child_ptr != NULL)
{
len = read(pipe1_fd[0],child_buf,255);
child_buf[len] = '\0';
printf("Parent: %s\n",child_buf);

if(i == 1)
{
time(&curtime);
len = sprintf(child_buf, "%s %s", child_ptr, ctime(&curtime));
child_buf[len-1] = '\0';
write(pipe2_fd[1],child_buf,strlen(child_buf));
}
else
{
write(pipe2_fd[1],child_ptr,strlen(child_ptr));
}

child_ptr = child_talks[++i];
}

close(pipe1_fd[0]);
close(pipe2_fd[1]);
exit(0);
}
else //parent
{
//pipe1_fd[1] is used to write, pipe2_fd[0] is used to read
close(pipe1_fd[0]);
close(pipe2_fd[1]);

j = 0;
parent_ptr = parent_talks[j];
while(parent_ptr != NULL)
{
write(pipe1_fd[1],parent_ptr,strlen(parent_ptr));
len = read(pipe2_fd[0],parent_buf,255);
parent_buf[len] = '\0';
printf("Child: %s\n", parent_buf);
parent_ptr = parent_talks[++j];
}

close(pipe1_fd[1]);
close(pipe2_fd[0]);
wait(&child_status);
exit(0);
}
}

If you enjoyed this post Subscribe to our feed

No Comment

張貼留言