Ash*_*hot 4 c gcc compiler-errors sigchld
我从以下文档复制了此程序:https : //docs.oracle.com/cd/E19455-01/806-4750/signals-7/index.html
#include <stdio.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/resource.h>
void proc_exit()
{
int wstat;
union wait wstat;
pid_t pid;
while (TRUE) {
pid = wait3 (&wstat, WNOHANG, (struct rusage *)NULL );
if (pid == 0)
return;
else if (pid == -1)
return;
else
printf ("Return code: %d\n", wstat.w_retcode);
}
}
main ()
{
signal (SIGCHLD, proc_exit);
switch (fork()) {
case -1:
perror ("main: fork");
exit (0);
case 0:
printf ("I'm alive (temporarily)\n");
exit (rand());
default:
pause();
}
}
Run Code Online (Sandbox Code Playgroud)
运行时出现gcc main.c此错误:
main.c: In function ‘proc_exit’:
main.c:9:13: error: conflicting types for ‘wstat’
union wait wstat;
^~~~~
main.c:8:6: note: previous declaration of ‘wstat’ was here
int wstat;
^~~~~
main.c:9:13: error: storage size of ‘wstat’ isn’t known
union wait wstat;
^~~~~
main.c:12:9: error: ‘TRUE’ undeclared (first use in this function)
while (TRUE) {
Run Code Online (Sandbox Code Playgroud)
据我了解wstat是两次定义。这是否意味着文档不正确?以及如何解决?
是的,该代码已损坏。我不知道这是什么意思union wait wstat;。也许是文档作者的一些复制粘贴错误。谁知道。IMO总的来说代码编写得很差。
无论如何,这是代码实际尝试执行的操作:
int wstat;
pid_t pid;
while (1) {
pid = wait3(&wstat, WNOHANG, NULL);
if (pid == 0 || pid == -1)
return;
printf("Return code: %d\n", wstat);
}
Run Code Online (Sandbox Code Playgroud)