我编写函数以防止运行具有相同配置的应用程序的两个实例(fifo文件):
if( !filename_specified ) {
char *fifofile = get_fifo_filename( config_get_uid( ct ) );
int fifofd;
if( !fifofile ) {
lfprintf( stderr, _("%s: Cannot allocate memory.n"), argv[ 0 ] );
return 0;
}
/* negative_return_fn: Function "open(fifofile, 2049)" returns a negative number */
fifofd = open( fifofile, O_WRONLY | O_NONBLOCK );
if( fifofd >= 0 ) {
lfprintf( stderr, _("Cannot run two instances of application with the same configuration.n") );
close( fifofd );
return 0;
}
/* negative_returns: "fifofd" is passed to a parameter that cannot be negative */
close( fifofd );
}
我的代码收到以下警告:
负值用作需要正值的函数的参数。
> 如果open()
返回负值,则失败。如果失败open()
则返回的值不是有效的文件描述符,该文件尚未打开,因此不需要对其进行close()
编辑。
通过仅将fifofd
传递给close()
(如果它大于或等于0
,即对open()
成功的相应调用来解决此问题:
if (0 <= fifofd)
{
if (-1 == close(fifofd))
{
perror("close() failed");
}
}