多进程-PCB-PID


定义

PCB

task_struct

PID

#include 
#include      // pid_t getpid(void)
#include     // pid_t

int main(int argc, char *argv[]) {
    pid_t pid = getpid();

    printf("PID:%d\n", pid);

    return 0;
}
// 
#include 
#include     // bool
#include 
#include 

// 静态函数作用:
static char * pid_file = "/var/run/test.pid";

static bool check_pid(char * pid_file) {
    struct stat stb;
    FILE * pid_f;

    if (stat(pid_file, &stb) == 0) {
        pid_f = fopen(pid_file, "r");
        if (pid_f) {
            char buf[64];
            pid_t pid = 0;
            memset(buf, 0, sizeof(buf));
            if (fread(buf, 1, sizeof(buf), pid_f)) {
                buf[sizeof(buf) - 1] = '\0';
                pid = atoi(buf);
            }
            fclose(pid_f);
            if (pid && kill(pid, 0) == 0) {
                return 1;
            }
        }
        printf("Removing pid file '%s', process not running", pid_file);
        unlink(pid_file);
    }
    return 0;
}


int main(int argc, char *argv[]) {
    FILE * fd = fopen(pid_file, "w");

    if (fd) {
        fprintf(fd, "%u\n", getpid());
        fclose(fd);
    }
    if (check_pid(pid_file)) {
        printf("Test is already running (%s exists)", pid_file);
    } else {
        printf("Test is NOT running (%s NOT exists)", pid_file);
    }
    unlink(pid_file);   // 删除文件
    return 0;
}