📄 10-1.c
字号:
#include <unistd.h>
#include <sys/types.h>
int main(void)
{
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
{
printf("\n");
//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();
}
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();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -