【问题标题】:Executing a threading program in Linux在 Linux 中执行线程程序
【发布时间】:2016-08-25 07:19:21
【问题描述】:

这是我的代码。当我尝试编译时,它给了我很多错误。我使用了 gcc -o 进程 process.c -lpthread。谁能帮我?我试过包括“mamespace”,但这没有帮助。

#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);
}

【问题讨论】:

  • 这里提供调试帮助的理念是要求Minimal, Complete, and Verifiable Example。当您将代码缩减为更小的部分以重现这些“编译错误”中的第一个(您的问题中没有另外描述)时,您将学到很多关于调试的知识。
  • @hardmath process.c:39:1:错误:程序 process.c:39:1 中的杂散“\240”:错误:程序 process.c:39 中的杂散“\302”: 1:错误:程序 process.c:40:1 中的流浪 '\240':错误:程序中的流浪 '\302' for(j=0; j

标签: linux multithreading process


【解决方案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);
       ^

所以修复错误并重建它。

【讨论】:

    猜你喜欢
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多