2016-04-30 132 views
0

這是我的代碼。當我嘗試編譯時,它給了我許多錯誤。我用gcc -o進程process.c -lpthread。誰能幫我?我曾嘗試過使用「mamespace」,但這沒有幫助。在Linux中執行線程程序

#include <stdio.h> 
#include <stdlib.h> 
#include <sys/types.h> 
#include <sys/wait.h> 
#include <unistd.h> 


int main() 
{ 
  int i, j; 
  int Num_of_children = 0; 
  pid_t pid[10]; 
  pid_t return_pid; 

  return_pid = fork(); 
  if(return_pid > 0) { 
     pid[Num_of_children] = return_pid; 
     Num_of_children = Num_of_children + 1; 
  } 

  return_pid = fork(); 
  if(return_pid > 0) { 
     pid[Num_of_children] = return_pid; 
     Num_of_children = Num_of_children + 1; 
  } 
  else { Num_of_children = 0; } 

  if (Num_of_children > 0) { 
     return_pid = fork(); 
     if(return_pid > 0) { 
        pid[Num_of_children] = return_pid; 
        Num_of_children = Num_of_children + 1; 
     } 
     else { Num_of_children = 0; } 
  } 
   for(j=0; j<3; j++) { 
      sleep(1+1000*rand()/RAND_MAX); 
      printf("PID: %d, Iteration: d%\n", getpid(), i); 
   } 
  for(j=0; j<Num_of_children; j++) waitpid(pid[j], NULL, 0); 
} 
+0

此處提供調試幫助的原理是需要[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。當你將你的代碼縮減爲更小的部分時,你會學到很多關於調試的知識,這些部分會重現第一個「編譯錯誤」(在你的問題中沒有另外說明)。 – hardmath

+0

@hardmath process.c:39:1:錯誤:在程序中丟失'\ 240' process.c:39:1:錯誤:在程序中丟失'\ 302' process.c:39:1:error:stray (j = 0; j

回答

1

構建您的程序,並打開警告,即gcc -Wall -g -lpthread process.c -o process。然後你會發現你在你的代碼中犯的錯誤:

process.c: In function ‘main’: 
process.c:38:7: warning: unknown conversion type character 0xa in format [-Wformat=] 
     printf("PID: %d, Iteration: d%\n", getpid(), i); 
    ^
process.c:38:7: warning: too many arguments for format [-Wformat-extra-args] 
process.c:41:1: warning: control reaches end of non-void function [-Wreturn-type] 
} 
^ 
process.c:38:7: warning: ‘i’ may be used uninitialized in this function [-Wmaybe-uninitialized] 
     printf("PID: %d, Iteration: d%\n", getpid(), i); 
    ^

所以修復錯誤並重建它。