【发布时间】:2016-01-23 05:37:39
【问题描述】:
我正在练习信号,我已经在 ubuntu 上从 gcc 转移到 eclipse,我遇到了一些问题。下面的 gcc 代码对于 eclipse 编译得很好我得到了错误 “错误:从类型‘void (*)(int)’分配给类型‘union’时类型不兼容”
在网上看,由于编译器使用的是 C99 之前的版本,我发现有可能出错。所以我尝试让eclipse编译为C99版本,我发现下面的链接How do you configure GCC in Eclipse to use C99?
我尝试按照 SO 链接中的建议进行更改,但目前我的其他标志有一行显示 " -c -fmessage-length =0 "
如果我在该行之前或之后按照帖子的建议添加 -std=c99,编译器将无法找到文件本身
我假设我收到错误是因为编译器使用的是 C99 之前的版本。如果我在错误的方向上追逐,请纠正我,如果正确,将 -std=c99 添加到标志选项以使 eclipse 使用 C99 的正确方法是什么
编辑:根据我更改 sig_handler 参数时的答案,我能够在不添加 -std=c99 标志的情况下进行编译,但是按照建议添加,我遇到了编译错误。下面是编译行
gcc -O0 -g3 -Wall -c -fmessage-length=0 -std=c99 -MMD -MP -MF"
`odd_process.d" -MT"odd_process.d" -o "odd_process.o" "../odd_process.c`"
../odd_process.c: In function ‘main’:
../odd_process.c:13:2: error: unknown type name ‘sigset_t’
../odd_process.c:14:19: error: storage size of ‘sa’ isn’t know
n
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
void sighandler(int sig)
{
printf("signal has been caught \n ");
}
int main(void)
{
sigset_t block_signal, empty_signal;
struct sigaction sa;
pid_t childid;
int i;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
**/*for below line while running on eclipse I see error which says*/
/***error: incompatible types when assigning to type ‘union <anonymous>’ from type ‘void (*)(int)’** */**
**sa.__sigaction_handler = sighandler;**
stdbuf(stdout, NULL);
if (sigaction(SIGCHLD, &sa, NULL) == -1)
{
printf("value not passed to signal handler \n ");
}
sigemptyset(&block_signal);
sigaddset(&block_signal, SIGCHLD);
if (sigprocmask(SIG_SETMASK, &block_signal, NULL) == -1)
{
printf("error occurred while setting signal mask \n");
}
childid = fork();
printf("value of child id is -- %d ", childid);
switch(childid)
{
case -1:
printf("Error condition child creation did not happen properly \n");
exit(-1);
case 0:
printf(" Child got created and will print odd number !!! ");
sleep(5);
exit(1);
default:
printf(" parent gets created !!! \n ");
break;
}
sigemptyset(&empty_signal);
sigsuspend(&empty_signal);
printf(" parent will print \n ");
for(i = 0; i < 10; i++)
{
printf("%d ", i);
}
printf("\n");
return EXIT_SUCCESS;
}
【问题讨论】:
-
发布的代码丢失
#include <unistd.h> -
关于这一行:
stdbuf(stdout, NULL);我怀疑你真的想使用setbuf() -
这一行:
sa.sigaction_handler = sighandler;应该写成:`sa.sa_handler = sighandler; -
在添加缺少的头文件后,按照上面的注释更正行,然后在 eclipse 中编译,使用 `gcc -O0 -g3 -pedantic -Wall -Wextra -Wconversion -c -fmessage-length=0 - std=c99 -MMD -MP"
-
在阅读
sigaction()的手册页时,您将看到:sigaction(): _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE这意味着(至少)必须定义三个项目中的一个,否则头文件将跳过该行( s)sigaction()函数的原型。 (一般情况下,使用参数-std=gnu99或将#define appropriateName=value作为源文件的第一行会导致sigaction()函数被原型化。(我通常可以使用:#define _GNU_SOURCE导致头文件( s)生产一切)`