我改进了信号处理函数,但现在当我尝试通过gcc ./test2.c -Wall -Wextra
编译我的程序时,我收到以下内容;C警告:函数的隐式声明'flock'仅适用于两个flock()调用之一
./test2.c: In function 'end_app':
./test2.c:21: warning: implicit declaration of function 'flock'
./test2.c: In function 'main':
./test2.c:46: warning: implicit declaration of function 'usleep'
./test2.c:47: warning: implicit declaration of function 'close'
这是源代码test2.c中
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <fcntl.h>
static int end=0;
static int f;
static void end_app(int sig){
printf("Ending from sig#%d",sig);
struct sigaction si;
si.sa_handler=SIG_DFL;
si.sa_flags=0;
sigaction(SIGCHLD,&si,NULL);
sigaction(SIGTSTP,&si,NULL);
sigaction(SIGTTOU,&si,NULL);
sigaction(SIGTTIN,&si,NULL);
sigaction(SIGSEGV,&si,NULL);
sigaction(SIGTERM,&si,NULL);
sigaction(SIGHUP,&si,NULL);
flock(f,LOCK_UN); //compiler gives implicit declaration warning
printf("Ended\n");end=1;
}
void newsig(){
struct sigaction s,o;
o.sa_handler=SIG_DFL;
o.sa_flags=0;
s.sa_handler=&end_app;
s.sa_flags=SA_RESTART;
sigaction(SIGCHLD,&s,&o);
sigaction(SIGTSTP,&s,&o);
sigaction(SIGTTOU,&s,&o);
sigaction(SIGTTIN,&s,&o);
sigaction(SIGSEGV,&s,&o);
sigaction(SIGTERM,&s,&o);
sigaction(SIGHUP,&s,&o);
}
int main(){
f=open("xx.pid",O_WRONLY|O_CREAT|0x700);
flock(f,LOCK_EX); //function works here
printf("Started\n");
newsig();
while(1){
usleep(1000);
if (end==1){close(f);return 0;}
}
return 0;
}
我的问题是,为什么会编译器抱怨我的信号处理函数中使用的羊群,但它不抱怨主要功能?我能做些什么来纠正这个问题?我需要群集才能成功锁定和解锁文件。
[此'flock'手册页](http://man7.org/linux/man-pages/man2/flock.2.html)可能对您有所帮助。我建议你也查看其他功能的手册页。 –
'flock()'异步信号安全吗?它没有在Linux'signal'手册页(http://man7.org/linux/man-pages/man7/signal.7.html)中列出为异步信号安全的,但我不明白为什么它不会因为'fcntl()'也可以用来执行文件锁定,'fcntl()'是异步信号安全的。 –