2013-07-26 54 views
1

在C程序中,我有一個菜單,其中有一些選項可供選擇,由字符表示。有一個選項可以分叉進程,並運行一個函數(我們可以說它在後臺運行)。此功能在後臺運行,在某些情況下,可以要求用戶輸入數據。讀取同一stdin的兩個進程

我的問題是:當主進程詢問數據(或選項)並且子進程也在詢問數據時,我無法正確發送數據。

你對如何處理這個問題有什麼想法嗎?

我會添加一些代碼的結構的(我不能發佈這一切,因爲是大約600行代碼):

int main(int argc, char *argv[]) 
{ 
    // Some initialization here 
    while(1) 
    { 
     scanf("\n%c", &opt); 

     switch(opt) 
     { 
      // Some options here 
      case 'r': 
       send_command(PM_RUN, fiforfd, fifowfd, pid); 
       break; 
      // Some more options here 
     } 
    } 
} 

void send_command(unsigned char command, int fiforfd, int fifowfd, int pid) 
{ 
    // Some operations here 
    if(command == PM_RUN) 
    { 
     time = microtime();     
     childpid = fork(); 
     if(childpid == -1) 
     { 
      // Error here 
     } 
     else if(childpid == 0) 
     { 
      // Here is the child 
      // Some operations and conditions here 
      // In some condition, appears this (expected a short in hexadecimal) 
      for(i = 0; i < 7; ++i) 
       scanf("%hx\n",&data[i])); 
      // More operations 
      exit(0); 
      } 
     } 
    } 
+0

看你能告訴我們你做了什麼,也許所有的孩子你應該看看'pipe'' dup'和'select' – Alexis

+0

你很可能不得不使用某種鎖定機制來鎖定資源標準輸入。最好的鎖定機制(例如互斥鎖)取決於你做了什麼。 – urzeit

+0

@Alexis我看不到如何使用pipe,dup和select來做我想做的事。可能使用該代碼結構可以幫助我多一點。 – markmb

回答

1

它不工作,但它可以是一個開始的解決方案

void send_command(int *p) 
{ 
    pid_t pid; 

    pid = fork(); // check -1 
    if (pid == 0) 
    { 
     int  i = 0; 
     int  h; 
     int  ret; 
     char  buffer[128] = {0}; 

     dup2(p[0], 0); 
     while (i < 2) 
     { 
      if ((ret = scanf("%s\n", buffer))) 
      { 
       //get your value from the buffer 
       i++; 
      } 
     } 
     printf("done\n"); 
     exit(1); 
    } 
} 

在子進程中,你將讀取輸入中的所有內容,然後找到你需要的值。

int  main() 
{ 
    char opt; 
    int p[2]; 

    pipe(p); 
    while(1) 
    { 
     scanf("\n%c", &opt); 


     write(p[1], &opt, 1); 
     write(p[1], "\n", 1); 

     switch(opt) 
     { 
      // Some options here 
     case 'r': 
      { 
      send_command(p); 
      break; 
      } 
     default: 
      break; 
      // Some more options here 
     } 
    } 
} 

在當前情況下,您讀取的每個字符將被寫入在p [0]上讀取的子進程。

當然,如果你有很多子進程,你必須有一個文件描述符列表並寫入每個子進程(併爲每個子進程調用管道)。

好運

編輯:也許你應該看看namedpipe在父進程寫的所有內容,並在同一個

+0

我認爲添加管道會使事情變得複雜。儘管是一個很好的解決方案,但我認爲我會做的不那麼方便用戶,並避免使用此解決方案。無論如何,謝謝你的努力。 – markmb

相關問題