2010-10-30 47 views
0

這裏的故事:(!子進程的孩子)使用Unix的C程序問題,管道和處理

C編寫一個程序,創建一個子進程和granchild過程。 父進程應該讀取文件的內容,在運行該程序時該文件的名稱將作爲參數。 父親應該將閱讀的文本發送給孩子,該孩子需要轉換在'o'中找到的那些字符'a'。 已更改的文本將發送子孫給孫子(孫子)以計算文本中的行數和「o」字符數並在屏幕上輸出結果(以及可選的文件output.txt)。

所以我創建了一個文件,裏面有一些'a'字符,我真的不能將這些字符轉換爲'o'。

問題是我應該用什麼樣的命令來進行字符轉換?

任何幫助非常感謝。

這是我迄今所做的:

#include <stdio.h> 
#include <stdlib.h> 
#include <fcntl.h> 
#include <errno.h> 
#include <sys/types.h> 
#include <sys/wait.h> 
#include <unistd.h> 
#include <string.h> 
int main() { 
int fd_1[2],fd_2[2],pointer,pointer2,pid1,pid2,i,n; 
char filename[200]; 
char buffer[500000]; 

printf("Input filename:"); 
fflush(stdout); 

fflush(stdin); 

scanf("%s", filename); 

pointer = open(filename, O_RDONLY); 
    if (pointer == -1) { 
    printf("file does not exist\n"); 
    } 
pipe(fd_1); 
if (pipe(fd_1) == -1) { 
    perror("pipe"); 
    exit(1);  
    } 
pid1=fork(); 

switch(pid1){ 
    case -1: { 
     perror("fork"); 
     exit(10); 
     break; 
    } 
    case 0: { //child process 
     pipe(fd_2); 
     if (pipe(fd_2) == -1) { 
      perror("pipe"); 
      exit(1);  
     } 
     pid2=fork(); 
     switch(pid2) { 
      case -1: { 
       perror("fork"); 
       exit(10); 
       break; 
      } 
      case 0: { //grandchild process 
       close (fd_2[1]); 
       break; 
      } 
      default: { //child process 
       close (fd_1[1]); 
       dup2(fd_1[0],1); 
       pointer2 = open(buffer, O_WRONLY); 
       for (i=0; i< sizeof(buffer) ; i++) 
       if (buffer[i] == 'a') { 
        buffer[i] = 'o'; 
       }  
       write(fd_1[1], buffer, sizeof(buffer)); 
       wait(&pid2); 
       break; 
      } 
     } 
    } 
    default: { //parent process 
     close (fd_1[0]); 
     dup2(fd_1[1],0);  
     n = read(pointer, buffer, 200); 
     write(fd_1[1], buffer, n); 
     wait(&pid1); 
     break; 
    } 
} 
return 0; 
} 
+1

什麼是你的問題?聽起來你正在爲某人爲你做一件課程而釣魚。 – ak2 2010-10-30 19:05:03

+1

我用我需要得到答案的問題更新了主題。我想你是對的,沒有一個適當的問題,它可能看起來像我正在釣魚。我的道歉 – 2010-10-30 19:16:02

回答

1

假設孩子已經讀管道到緩衝區中,然後像:

for (int i = 0; i < bytes_read; ++i) 
{ 
    if (buffer[i] == 'a') 
     buffer[i] = 'o'; 
} 
+0

+1,...他可以產生孩子並創建管道,但在字節流中找不到'a'?奇怪的世界。 – slezica 2010-10-31 02:08:24

+0

@Santiago Lezica - 同意。還有其他的問題,但是丟失的管道讀取和迭代/寫入整個緩衝區,而不是讀取的內容看起來像當前的掛起。 – Duck 2010-10-31 05:19:13