我试图让这个打印文件的多行,空格替换为*,所有内容都翻译成大写。这应该通过管道和叉子来完成。为什么只打印第一行。
void writer(int inpipe)
{
char read_msg[BUFFER_SIZE];
pid_t pid;
int fd[2];
read(inpipe, read_msg, BUFFER_SIZE);
printf("%s\n",read_msg);
return;
}
void p2(int inpipe)
{
char read_msg[BUFFER_SIZE];
pid_t pid;
int fd[2];
if(pipe(fd) == -1) {
perror("Pipe error");
return;
}
pid = fork();
if(pid<0) { //error
perror("Fork Failed");
return;
}
else if(pid==0) { //child
close(fd[1]);
writer(fd[0]);
close(fd[0]);
return;
}
else { //parent, p2()
read(inpipe, read_msg, BUFFER_SIZE);
int i = 0;
while (read_msg[i] != '\0') {
read_msg[i] = toupper(read_msg[i]);
i++;
}
close(fd[0]);
write(fd[1],read_msg,(unsigned long)(strlen(read_msg)+1));
close(fd[1]);
}
return;
}
void p1(int inpipe)
{
char read_msg[BUFFER_SIZE];
pid_t pid;
int fd[2];
if(pipe(fd) == -1) {
perror("Pipe error");
return;
}
pid = fork();
if(pid<0) { //error
perror("Fork Failed");
return;
}
else if(pid==0) { //child
close(fd[1]);
p2(fd[0]);
close(fd[0]);
return;
}
else { //parent, p1()
read(inpipe, read_msg, BUFFER_SIZE);
int i = 0;
while (read_msg[i] != '\0') {
if ((read_msg[i] == ' '))
read_msg[i] = '*';
i++;
}
//printf("%s\n",read_msg);
close(fd[0]);
write(fd[1],read_msg,(unsigned long)(strlen(read_msg)+1));
close(fd[1]);
}
return;
}
int main(int argc, char **argv) {
pid_t pid;
int fd[2];
if(pipe(fd) == -1) {
perror("Pipe error");
return 1;
}
pid = fork();
if(argv[1] != NULL) {
char const* const fileName = argv[1];
FILE* file = fopen(fileName, "r");
char line[BUFFER_SIZE];
while (fgets(line, sizeof(line), file)){
if(pid<0) { //error
perror("Fork Failed");
return 1;
}
else if(pid==0) { //child
close(fd[1]);
p1(fd[0]);
close(fd[0]);
}
else { //parent, main(), reader
//reading from the file and put it into the pipe[1]
close(fd[0]);
write(fd[1],line,strlen(line)+1);
close(fd[1]);
}
}
}
else
printf("No file detected.\n");
return EXIT_SUCCESS;
}