【发布时间】:2018-05-23 05:50:20
【问题描述】:
正如标题所说,我正在尝试用 C 创建一个程序,其中 2 个子进程研究一个元音 (son2) 和一个辅音 (son2)。为了进行研究,我使用了 2 个功能,第一个研究元音,第二个研究辅音。 我从命令行给程序 3 个文件:
-1°是存储元音和辅音组合的文件
-2° 是存储所有创建的元音的文件
-3°是存储所有创建的辅音的文件
程序编译没有错误/警告,但它没有正确完成研究,这里是一个例子:
-第一个文件:qwerty
-第二个文件:ey
-第三个文件:qr
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <ctype.h>
int test_vowel(char ch)
{
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'y')
return(1);
else
return(0);
}
int main(int argc, char *argv[])
{
char c, d;
int s;
pid_t pid1 = 10, pid2 = 10;
if((pid1 = fork()) < 0)
{
printf("Error in the creation of the first fork\n");
_exit(0);
}
if(pid1 > 0)
{
if((pid2 = fork()) < 0)
{
printf("Error in the creation of the second fork\n");
_exit(0);
}
}
int input = open(argv[1],O_RDONLY);
int output1 = open(argv[2],O_RDWR | O_CREAT | O_TRUNC, 0666);
int output2 = open(argv[3],O_RDWR | O_CREAT | O_TRUNC, 0666);
if(pid2 == 0)
{
while((s = read(input, &c, 1)) != 0)
{
if(test_vowel(tolower(c)) == 1)
{
printf("I've read a vowel = %d\n", d);
write(output1, &c, 1);
}
}
}
if(pid1 == 0)
{
while((s = read(input, &d, 1)) != 0)
{
if(test_vowel(tolower(d)) == 0)
{
printf("I've read a consonant = %d\n", d);
write(output2, &d,1);
}
}
}
}
我使用这些命令来编译它
gcc c.c
./a.out c.txt v.txt b.txt
提前感谢您的帮助!
编辑(最终) 遵循 David C. Rankin 的所有提示简化了代码(现在正在运行)
【问题讨论】:
-
使用
tolower (ch)会将if条件的数量减少2 倍。为什么是2 个函数而不是1 个?只需if (isalpha(ch)) { ch = tolower(ch); if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') return 1; else return 2; }(或任何你想表示的辅音或元音) -
我不得不说我的书从来没有引用过这个函数,谢谢你的提示!