2017-04-08 30 views
-2

我是新進程。我讀了很多,但我真的不明白它是如何工作的。我嘗試爲char字符串中的每個元音創建一個進程。我必須從該字符串中刪除所有元音。我知道我必須使用叉子,但我不知道如何。我試圖編寫代碼,但我收到的是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; 
} 

我並不瞭解孩子的過程,一切如何。非常感謝你!

+1

C或C++?他們是不同的語言,有不同的答案。 – aschepler

+0

對不起C,我錯了。 – mary

回答

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; 
} 
相關問題