2016-04-30 134 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); 
    ^

所以修复错误并重建它。