I want to create a function that, given a filename, creates a .PID file into a specific existing .pid directory using the filename. the directory is inside the main directory of the project and is visible. what i wrote is
int CreaPidFile(char *filename){
if(filename==NULL)
return -2;
int dim=0;
char path[7]="./pid/";
char suffix[5]=".pid";
char *pathfilename=NULL;
dim= strlen(filename);
if(dim<=0)
return -3;
dim+=strlen(path);
dim+=strlen(suffix);
dim++;
pathfilename=(char *)malloc(dim*sizeof(char));
strcpy(pathfilename, path);
strcat(pathfilename, filename);
strcat(pathfilename, suffix);
pathfilename[dim-1]='\0';
printf("pathfilename: %s, dim=%d\n", pathfilename, dim);
fflush(stdout);
int fd;
int pid=getpid();
char* charpid;
charpid=malloc(21*sizeof(pid));
memset(charpid, 0, sizeof(char));
sprintf(charpid, "%d", pid);
charpid[20]='\0';
printf("pid=%d, charpid=%s\n", pid, charpid);
if((fd=open(pathfilename, O_RDWR|O_CREAT|O_EXCL|O_TRUNC, S_IRUSR|S_IWUSR))<0){
free(pathfilename);
return -1;
}
if((write(fd, charpid, 21))<0){
free(pathfilename);
return -1;
}
free(pathfilename);
free(charpid);
return fd;
}
I have two types of error:
first, valgrind print this output error:
Syscall param write(buf) points to uninitialised byte(s)
==2680== at 0x486FA77: write (write.c:26)
==2680== by 0x10A679: CreatePidFile (utility.c:85)
==2680== by 0x10934D: main (main_supermarket1.c:27)
==2680== Address 0x4a704b5 is 5 bytes inside a block of size 84
alloc'd
==2680== at 0x483C7F3: malloc (in /usr/lib/x86_64-linux-
gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==2680== by 0x10A60E: CreaPidFile (utility.c:76)
==2680== by 0x10934D: main (main_supermercato1.c:27)
second error, although the file is .pid, it remains a binary file so information is stored as binary.
If i print on stdout the values of pid and charpid, they are the same. Any suggestion on how to solve the problem?