函数‘wait’的隐式声明

28

我得到了一个警告 > 隐式声明函数'wait',但当我运行程序时,它可以正常工作。我想知道为什么会出现这个警告?

提前致谢。

编辑:我忘记添加库了。

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


void create (char* program, char** arg_list)
{
  /* put your code here */
  pid_t childPid;
  int status;

  if((childPid = fork()) < 0){
    printf("Failed to fork() --- exiting...\n");
    exit(1);
  }
  else if (childPid == 0){ // --- inside the child process
    if(execvp(program, arg_list) < 0){ // Failed to run the command
      printf("*** Failed to exec %s\n", program);
      exit(1);
    }
  }
  else{ // --- parent process
    while(wait(&status) != childPid)
      printf("...\n");
  }
}

你漏掉了函数的#include语句。 - Barmar
2个回答

53

你可能缺少wait(2)的头文件:

  #include <sys/types.h>
  #include <sys/wait.h>

1
谢谢,我忘记了等待库。 - AyeJay
如果您没有使用从wait函数调用返回的任何类型,那么sys/types.h是否必要? - MichaelM
1
@MichaelM 我的回答是基于 Linux man 页面 当时 的内容。但是自从这个提交之后,它已经被删除了。早期包含它的原因是由于 wait 使用的类型(如 pid_t)。[续] - P.P
1
@MichaelM 但是包括必要的类型应该由sys/wait.h本身处理,而不需要用户去包含它们。 [POSIX] (https://pubs.opengroup.org/onlinepubs/9699919799/functions/wait.html)也不需要`sys/types.h`。总之,在使用`wait`时不需要`sys/types.h`! - P.P
@P.P 感谢澄清!我只是想确保我理解得正确。我能够在没有 sys/types.h 的情况下编译,并且没有遇到任何问题,但我想确保我没有意识到的“隐藏”问题。 - MichaelM

11

您需要放置:

#include <sys/types.h>
#include <sys/wait.h>

在程序顶部获取函数的声明。

这在man页面中有说明。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接