Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
526 views
in Technique[技术] by (71.8m points)

fopen - C create a PID file non binary

I want to create a function that, given a string filename, creates the file called filename.PID inside the ./pid directory.

    #define DEBUG 1
    //PRINT_DEBUG just print the string in stderr

    int CreatePidFile(char *filename){
    if(DEBUG){
        DEBUG_PRINT("CreatePidFile: start
");
    }
    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]='';  //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
");
        }
        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
");
        }
        fclose(pidfile);
        free(pathfilename);
        return -2;
    }
    fclose(pidfile);
    free(pathfilename);
    if(DEBUG){
            DEBUG_PRINT("CreatePidFile: end
");
    }
    return 0;
}

The main I use is:


    int main(){
    printf("create pid: start
");
    char *filepid = "test_pid_file";
    if((CreatePidFile(filepid))!=0){
        printf("file not created
");
    }
    else{
        printf("test_utility: file is created
");
    }
    return 0;
}

At the end of the program, the file is created but is a binary file. I want a text file.

question from:https://stackoverflow.com/questions/65882446/c-create-a-pid-file-non-binary

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, you do a binary write of the pid:

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

If you want text, just use fprintf:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...