我是Processes的新手。我读了很多,但我真的不明白它是如何工作的。我尝试在char字符串中为每个元音创建一个进程。我必须删除该字符串中的所有元音。我知道我必须使用fork,但我不知道怎么做。我试着写代码,但收到的是Core Dumped。
#include <unistd.h>
#include <stdio.h>
#include <string.h>
char sir[100];
int vocal(char x)
{
if(x=='a' || x=='e' || x=='i' || x=='o' || x=='u' || x=='A'||
x=='E' || x=='I' || x=='O' || x=='U')
return 1;
return 0;
}
int main(){
printf("Read the text: \n");
read(1,sir,100); // file descriptor is 1;
pid_t a_Process;
for(int i=0;i<strlen(sir);i++)
{
if(vocal(sir[i])==1)
{
a_Process=fork();
for(int j=i;j<strlen(sir)-1;i++)
sir[j]=sir[j+1];
}
}
printf("%s",sir);
return 0;
}
我不明白孩子的过程和一切如何。非常感谢你!
答案 0 :(得分:0)
试试这段代码:
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char sir[100];
int vocal(char x)
{
if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u' ||
x == 'A' || x == 'E' || x == 'I' || x == 'O' || x == 'U')
return 1;
return 0;
}
int main()
{
int i, j, pid_status;
printf("Read the text: \n");
// read(1,sir,100); // file descriptor is 1;
fgets(sir, 100, stdin);
pid_t a_Process;
for (i = 0; i < strlen(sir); i++)
{
if (vocal(sir[i]) == 1)
{
printf("detected a vowel\n");
a_Process = fork();
if (a_Process == -1)
{
fprintf(stderr, "Can't fork a process.\n");
return 1;
}
if (a_Process)
{
printf("Starting a new child .... \n");
for (j = i; j < strlen(sir) - 1; j++)
sir[j] = sir[j + 1];
}
// The following statement is needed such that
// child process starts one after the other.
if (waitpid(a_Process, &pid_status, 0) == -1)
{
printf("Error waiting for child process.\n");
}
}
}
printf("%s", sir);
return 0;
}