我正在使用子进程和父进程编写程序,该进程允许用户键入一串字符,然后将它们转换为全大写字母。父进程提示用户输入字符串,通过管道将其发送到子进程,然后子进程使它们全部为大写。
该程序运行正常,唯一的问题是它需要一次又一次地运行而不退出。换句话说,我需要父进程在子进程完成后继续。我尝试使用各种while(1)循环无济于事。有关如何实现这一点的任何想法?谢谢!
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void parent(int filename);
void child(int filename);
main(int argc, char * argv[])
{
int the_pipe[2];
pid_t process_id;
//create the pipe
if (pipe(the_pipe) < 0) {
fprintf(stderr, "PIPE FAILED!\n");
return -1;
}
//fork to child process
process_id = fork();
if (process_id == (pid_t) 0) { //this is the child
close(the_pipe[1]); //close writing end
child(the_pipe[0]); //call the child process
return 0;
}
else if (process_id < (pid_t) 0) {
fprintf(stderr, "FORK FAILED!\n");
return -1;
}
else { //this is the parent
close(the_pipe[0]); //close reading end
parent(the_pipe[1]); //call the parent process
return 0;
}
}
void parent(int filename)
{
FILE * fp;
char input_line[256]; //string for user to fill
fp = fdopen(filename, "w"); //open file for writing
printf(" >> "); //prompt the user
fgets(input_line, 256, stdin); //get user input
fprintf(fp, "%s", input_line); //write user input to file
fclose(fp); //close the file
wait(); //wait for child process to finish
}
void child(int filename)
{
FILE * fp;
char string[256]; //original string from pipe
char upper[256]; //new string (all upper-case)
int i; //array index
fp = fdopen(filename, "r"); //open file for reading
fgets(string, 256, fp); //get the string from the pipe
for (i = 0; i < 256; i++) { //turn all lower-case to upper-case
if ((string[i] > 96) && (string[i] < 123))
upper[i] = string[i] - 32;
else
upper[i] = string[i];
}
printf(" %s", upper); //print out the new string
fclose(fp); //close the file
}