c - C创建一个非二进制的PID文件
问题描述
我想创建一个函数,给定一个字符串文件名,在./pid目录中创建名为filename.PID的文件。
#define DEBUG 1
//PRINT_DEBUG just print the string in stderr
int CreatePidFile(char *filename){
if(DEBUG){
DEBUG_PRINT("CreatePidFile: start\n");
}
char *path = "./pid/";
char *post = ".PID";
FILE *pidfile;
char *pathfilename;
int N=strlen(path)+strlen(filename)+strlen(post)+1;
if((pathfilename=(char *)malloc(N*sizeof(char)))==NULL){
return -3;
}
strcpy(pathfilename, path);
strcat(pathfilename, filename);
strcat(pathfilename, post);
pathfilename[N-1]='\0'; //just to be sure that it has the final string char
if((pidfile = fopen(pathfilename, "w"))==NULL){
if(DEBUG){
DEBUG_PRINT("CreatePidFile: impossible to create il file\n");
}
free(pathfilename);
return -1;
}
int pid=getpid();
if((fwrite((void *)&pid, sizeof(int), 1, pidfile))==0){
if(DEBUG){
DEBUG_PRINT("CreatePidFile: impossible to write pid in pidfile\n");
}
fclose(pidfile);
free(pathfilename);
return -2;
}
fclose(pidfile);
free(pathfilename);
if(DEBUG){
DEBUG_PRINT("CreatePidFile: end\n");
}
return 0;
}
我使用的主要是:
int main(){
printf("create pid: start\n");
char *filepid = "test_pid_file";
if((CreatePidFile(filepid))!=0){
printf("file not created\n");
}
else{
printf("test_utility: file is created\n");
}
return 0;
}
在程序结束时,文件被创建,但它是一个二进制文件。我想要一个文本文件。
解决方案
好吧,您对以下内容进行二进制写入pid
:
fwrite((void *)&pid, sizeof(int), 1, pidfile)
如果你想要文本,只需使用fprintf
:
fprintf(pidfile, "%d", (int)pid);
推荐阅读
- angular - 角度:LOCATION_INITIALIZED 它是什么,为什么要使用它?
- c# - 从 OPENID 和 SAML 2.0 中选择什么
- javascript - Javascript根据数组的长度和键值修改数组
- wordpress - Wordpress 商店定位器 HTTP403
- php - 搜索错误:选择:内存耗尽 | 狮身人面像搜索
- windows - 如何配置 Windows 性能数据收集器以正确记录 DST?
- laravel - Laravel 在刀片中使用 {!!nl2br(e())!!} 是否安全
- sapui5 - 如何将 XML 片段添加到 XML 视图?
- delphi - 在 Delphi 6 中使用 Indy 8.0.26 的 PUT 命令
- scala - Scala 定义的命名约定