首页 > 解决方案 > 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;
}

在程序结束时,文件被创建,但它是一个二进制文件。我想要一个文本文件。

标签: cfopenfwritepid

解决方案


好吧,您对以下内容进行二进制写入pid

fwrite((void *)&pid, sizeof(int), 1, pidfile)

如果你想要文本,只需使用fprintf

fprintf(pidfile, "%d", (int)pid);

推荐阅读