My last question作为背景。 我试图绕过“ fopen()”,但是gcc给了我这个错误,而“ remove()”没有问题。
错误:“ fopen”的类型冲突 fopen(const char *路径名,const char *模式) ^ 在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中声明。但是,为什么会有所不同?
答案 0 :(得分:0)
我找到了解决方案。 “ fopen()”的返回值应该是FILE *,而不是我错误地使用了int。