【问题标题】:What is the error in the program?程序中的错误是什么?
【发布时间】:2015-08-20 03:03:27
【问题描述】:

我用 C 语言编写了这个基础的分叉程序。但是编译器向我发出错误。代码是

#include<stdio.h>
#include<sys/stat.h>
#include<ctype.h>

void childProcess(){
    printf("From child process with process id %d\n", getpid());
}


void parentProcess(){
    printf("Parent Process with id %d\n", getpid());
    pid_t pid = fork();
    if (pid == 0){
        childProcess();
    } else if (pid > 0){
        printf("Parent spawned process %d\n", pid);
    } else{
        printf("Forking isn't supported!\n");
    }

}

int main(){
    parentProcess();

}

错误是

C:\Users\ADMINI~1\AppData\Local\Temp\ccORJc6N.o forking.c:(.text+0x3e): undefined reference to `fork'

【问题讨论】:

    标签: c system fork


    【解决方案1】:

    您使用的是 Windows,看起来您无法在 Windows 上执行此操作。以下是一些相关的帖子:

    这些是谷歌搜索错误时的前三个链接:undefined reference to `fork'

    【讨论】:

      【解决方案2】:

      你缺少一个库:

      将此添加到代码的顶部

      #include  <sys/types.h>
      

      【讨论】:

      • 这是一个链接器错误。添加标题不会解决问题。
      • 他没有指定窗口,他的错误与 pid_t 引用有关。如果它在 Windows 上,那么是的,你是对的
      • 其实这是程序的错误。另一个错误,当前投票最多的答案,实际上是用户选择操作系统的错误。请记住,问题是关于程序中的错误,缺少包含实际上可能会导致此类链接器错误...假设操作系统正确,@JimLewis,这实际上会修复错误。
      【解决方案3】:

      为了统一我迄今为止看到的最佳答案(不一定是最受欢迎的):

      我在程序中发现了另一个错误。 %d 告诉 printf 打印 int 类型的参数,但您提供的实际类型是 pid_t。根据the printf manual(我强烈建议您阅读并充分理解多次,以便编写更好的代码;您会学到很多),“如果任何参数不是正确的类型相应的转换规范,行为未定义。”您需要显式转换。例如:

      printf("From child process with process id %d\n", (int) getpid());
      printf("Parent Process with id %d\n", (int) getpid());
      printf("Parent spawned process %d\n", (int) pid);
      

      转换为int 本身就是一个错误;根据the &lt;sys/types.h&gt; header manual,符合 POSIX 的实现“应支持一个或多个编程环境,其中 blksize_tpid_tsize_tssize_tsuseconds_tuseconds_t 的宽度不大于类型 long 的宽度。"在这样的环境中,转换为long 并使用相应的%ld(顺便说一下,这是一个ell)指令会更合适:

      printf("From child process with process id %ld\n", (long) getpid());
      printf("Parent Process with id %ld\n", (long) getpid());
      printf("Parent spawned process %ld\n", (long) pid);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-26
        • 1970-01-01
        • 2019-10-16
        • 2023-04-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多