#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>
#include <dirent.h>
#include <sys/types.h>
#include <pwd.h>
#include <sys/stat.h>
#include <fcntl.h>
char* sha1_hash(char *input_url, char *hashed_url){
unsigned char hashed_160bits[20];
char hashed_hex[41];
int i;
SHA1(input_url, strlen(hashed_hex), hashed_hex);
for(i=0; i<sizeof(hashed_160bits);i++)
sprintf(hashed_hex + i*2, "%02x", hashed_160bits[i]);
strcpy(hashed_url, hashed_hex);
return hashed_url;
}
char* getHomeDir(char *home) {
struct passwd *usr_info = getpwuid(getuid());
strcpy(home, usr_info->pw_dir);
return home;
}
int main()
{
char* token; //To use strtok
char* input_url;
char* hash_ptr;
char hash_name[3], *hash_txt;
char* home;
DIR *Pdir;
int fd;
Pdir = opendir(getHomeDir(home));
if(Pdir == NULL)
{
printf("Open ERROR\n");
return 0;
}
umask(0000);
mkdir("cache", 0777);
do
{
printf("input URL>");
scanf("%s",input_url);
hash_ptr = sha1_hash(input_url, hash_ptr);
for(int i=0; i<3; i++)
{
hash_name[i] = hash_ptr[i];
}
hash_ptr[2] = ' '; //To use Strtok
token = strtok(hash_ptr, " ");
while(token != NULL)
{
token = strtok(NULL, " ");
}
hash_txt = token;
umask(0000);
mkdir(hash_name, 0777);
fd = open(hash_txt, O_CREAT, 0777);
closedir(Pdir);
close(fd);
}while(strcmp(input_url, "bye"||"BYE") != 0);
}
When this program runs. It makes cache directory and get input(URL links) and converts URL Links into 41 range hashed hex. first 3 elements of array are directory's name(stored in cache directory) and left 38 is stored in (cache/00x(eg)) as a file name.
I don't know how to do debug this code with gdb. when i input "gcc -g -o test cache_proxy.c" it don't returns test file. so i can't find the problem line.
Please let me know.
How can i fix segmentation fault(core dump)?
You can fix that by not using uninitialized pointers, for example
char* input_url;
…
scanf("%s",input_url);
Such errors can be avoided by adding -Wall
to your compilation command and removing the sources of the warnings you get. Chances are that thereafter you won't need to debug.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.