- 论坛徽章:
- 0
|
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
int pipe1_fd[2] = { 0};
int pipe2_fd[2] = { 0};
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] = { '\0'};
char child_buf[256] = { '\0'};
char *parent_ptr = NULL;
char *child_ptr = NULL;
int i = 0;
int j = 0;
int len = 0;
int child_status = 0;
time_t curtime;
if(pipe(pipe1_fd) < 0)
{
printf("pipel create erro\n" );
return -1;
}
if(pipe(pipe2_fd) < 0)
{
printf("pipe2 create error\n" );
return -1;
}
if(fork() == 0)
{
printf("\n" );
close(pipe1_fd[1]);
close(pipe2_fd[0]);
i = 0;
child_ptr = child_talks;
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[0]);
exit(0);
}
else
{
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);
}
return 0;
}
重点不明,time函数和wait函数,网上查了,还是不太明白,请帮帮我,谢谢大伙。
[ 本帖最后由 zhanglupanda 于 2007-7-19 20:01 编辑 ] |
|