练习
创建一个子进程,负责循环从管道中读取数据,父进程从键盘读取数据后,写入到管道中,输入 “quit” 字符串时退出
创建一个子进程,负责循环从管道中读取数据,父进程从键盘读取数据后,写入到管道中,输入 “quit” 字符串时退出
登录后即可发布作业,立即登录
我的作业
全部作业 4
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int pipefd[2];
pid_t pid;
if(pipe(pipefd) == -1)
{
perror("pipe() error!\n");
}
pid = fork();
if(pid == -1)
{
perror("fork error()!\n");
close(pipefd[0]);
close(pipefd[1]);
exit(-1);
}
else if(pid == 0)
{
close(pipefd[1]);
char buffer[100];
while(1)
{
memset(buffer, 0, sizeof(buffer));
read(pipefd[0], buffer, sizeof(buffer));
if(strcmp(buffer, "quit") == 0)
break;
printf("child process: %s\n", buffer);
}
close(pipefd[0]);
}
else
{
close(pipefd[0]);
char str[100];
while(1)
{
memset(str, 0, sizeof(str));
printf("input> ");
fgets(str, sizeof(str), stdin);
str[strlen(str)-1] = '\0';
#ifdef DEBUG
printf("[DEBUG] fgets: %s\n", str);
#endif
write(pipefd[1], str, strlen(str));
if(strcmp(str, "quit") == 0)
{
wait(NULL);
break;
}
}
close(pipefd[1]);
}
return 0;
}