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

68 lines
1.3 KiB
C
Raw Permalink Normal View History

2023-08-18 01:09:47 +08:00
#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]);
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;
}
close(fd[1]);
_exit(0);
}
else if (i == 1)
{
close(fd[1]);
while (1)
{
char buf[32] = "";
int len = read(fd[0], buf, 32);
if (len <= 0)
break;
if (strcmp(buf, "bye") == 0)
break;
printf("子进程 2 收到子进程 1 数据: %s\n", buf);
}
close(fd[0]);
_exit(0);
}
while (1)
{
int p_id = waitpid(-1, NULL, 0);
if (p_id == -1)
break;
}
return 0;
}