【发布时间】:2019-01-18 07:37:02
【问题描述】:
My last question 作为背景。 我试图环绕“fopen()”,但 gcc 给了我这个错误,而“remove()”没有问题。
错误:“fopen”的类型冲突 fopen(const char *pathname, const char *mode) ^ 在 file_io_operation_interception.c:2:0 包含的文件中: /usr/include/stdio.h:272:14:注意:先前的“fopen”声明是 这里 extern FILE *fopen (const char *__restrict __filename,
这是代码。
#define _GNU_SOURCE
#include <stdio.h>
#include <dlfcn.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 8080
#define MAXLINE 1024
static int (*real_fopen)(const char *pathname, const char *mode) = NULL;
static int (*real_remove)(const char *filename) = NULL;
static int (*real_close)(int fd) = NULL;
__attribute__((constructor))
void
my_lib_init(void)
{
real_fopen = dlsym(RTLD_NEXT,"fopen");
real_remove = dlsym(RTLD_NEXT,"remove");
real_close = dlsym(RTLD_NEXT,"close");
}
int
fopen(const char *pathname, const char *mode)
{
int fd;
// do whatever special stuff ...
fd = real_fopen(pathname, mode);
printf("open worked!\n");
char message[200];
char fidString[10];
sprintf(fidString, "%d ", fd);
strcat(message, fidString);
strcat(message, pathname);
sendMessage(message);
// do whatever special stuff ...
return fd;
}
int
remove(const char *filename)
{
int ret;
/*
if (real_remove == NULL)
real_remove = dlsym(RTLD_NEXT,"remove");
*/
// do whatever special stuff ...
printf("remove worked!\n");
sendMessage("remove message sent");
ret = real_remove(filename);
// do whatever special stuff ...
return ret;
}
int
close(int fd)
{
int ret;
/*
if (real_close == NULL)
real_close = dlsym(RTLD_NEXT,"close");
*/
// do whatever special stuff ...
printf("close worked!\n");
ret = real_close(fd);
// do whatever special stuff ...
return ret;
}
int
sendMessage(char *message)
{
int sockfd;
struct sockaddr_in servaddr;
// Creating socket file descriptor
if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
memset(&servaddr, 0, sizeof(servaddr));
// Filling server information
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
servaddr.sin_addr.s_addr = INADDR_ANY;
int n, len;
sendto(sockfd, (const char *)message, strlen(message),
MSG_CONFIRM, (const struct sockaddr *) &servaddr,
sizeof(servaddr));
printf("message sent\n");
close(sockfd);
return 0;
}
“remove()”函数可以正常工作,但“fopen()”不能。它们都在 stdio.h 中声明。但是,为什么会有差异呢?
【问题讨论】:
-
参见例如this
fopenreference 用于 C99 声明,这与您的不同。 -
哦,错误消息实际上包括“正确”声明。你为什么不简单地通过复制粘贴来使用它?信息非常明确。
-
@Someprogrammerdude 对不起,复制粘贴什么?你能详细说明一下吗?
-
查看您的错误消息,尤其是当它显示“注意:'fopen' 的先前声明在这里”时。这显示了真正的声明。复制粘贴(或者我之前链接到的使用正确 C99 关键字的参考)。
-
@Someprogrammerdude 好吧,我认为这不是问题所在。刚才我尝试使用“const char *restrict 文件名,const char *restrict 模式”,但没有成功。你看,我有点压倒一切“fopen()”。 GCC 错误消息:错误:在 'filename' fopen(const char *restrict filename, const char *restrict mode) 之前需要 ';'、',' 或 ')' ^ gcc: error: file_io_operation_interception.o: 没有这样的文件或目录
标签: c overriding system-calls