qfedu-linux-advanced-level/day4/homework/h3.c

73 lines
1.9 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 创建两个子进程一个子进程向从标准输入读取数据并向管道写入数据另一个子进程从管道读取数据并输出标准设备。当输入的数据是bye时则退出。父进程等待所有子进程退出。
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
int main()
{
int fd[2];
int f = pipe(fd);
if (f == -1)
{
perror("pipe");
_exit(1);
}
int i = 0;
for (; i < 2; i++)
{
pid_t pid = fork();
if (pid == 0)
break; // 子进程跳出循环
}
if (i == 0)
{
close(fd[0]); // 子进程1关闭管道读端
printf("请在子进程 1 中输入一段内容:\n");
while (1)
{
char msg[32] = "";
fgets(msg, 32, stdin);
msg[strcspn(msg, "\n")] = '\0'; // 去掉换行符
write(fd[1], msg, strlen(msg) + 1); // 包括'\0' , 写入管道
if (strcmp(msg, "bye") == 0)
break; // 如果输入 "bye"子进程1退出循环
}
close(fd[1]); // 关闭管道写端
_exit(0); // 子进程1退出
}
else if (i == 1)
{
close(fd[1]); // 子进程2关闭管道写端
while (1)
{
char buf[32] = "";
int len = read(fd[0], buf, 32);
if (len <= 0)
break; // 如果读取失败或到达文件末尾子进程2退出循环
if (strcmp(buf, "bye") == 0)
break; // 如果收到 "bye"子进程2退出循环
printf("子进程 2 收到子进程 1 数据: %s\n", buf);
}
close(fd[0]); // 关闭管道读端
_exit(0); // 子进程2退出
}
while (1)
{
int p_id = waitpid(-1, NULL, 0);
if (p_id == -1)
break; // 等待所有子进程退出后,父进程退出循环
}
return 0;
}