我编写函数来防止运行具有相同配置(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");
}
}
关于c - 参数不能为负(函数 : open),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19830367/