一 获取pid_t的字节长度
1 代码
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
pid_t pid;
cout <<"sizeof(pid_t)="<< sizeof(pid_t) << endl;
return 0;
}
2 运行结果
[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
sizeof(pid_t)=4
二 获取当前进程的ID
1 代码
#include <iostream>
#include <unistd.h>
using namespace std;
int main(int argc, char *argv[])
{
pid_t pid = getpid();
cout <<"pid="<<pid << endl;
return 0;
}
2 运行结果
[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
pid=1006
三 通过PID文件判断进程是否运行
1 代码
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
static char starter_pid_file_default[] = "/var/run/test.pid";
static bool check_pid(char *pid_file)
{
struct stat stb;
FILE *pidfile;
if (stat(pid_file, &stb) == 0)
{
pidfile = fopen(pid_file, "r");
if (pidfile)
{
char buf[64];
pid_t pid = 0;
memset(buf, 0, sizeof(buf));
if (fread(buf, 1, sizeof(buf), pidfile))
{
buf[sizeof(buf) - 1] = '\0';
pid = atoi(buf);
}
fclose(pidfile);
if (pid && kill(pid, 0) == 0)
{ /* such a process is running */
printf("pid=%d",pid);
return 1;
}
}
printf("removing pidfile '%s', process not running", pid_file);
unlink(pid_file);
}
return 0;
}
int main()
{
FILE *fd = fopen(starter_pid_file_default, "w");
if (fd)
{
fprintf(fd, "%u\n", getpid());
fclose(fd);
}
if (check_pid(starter_pid_file_default))
{
printf("test is already running (%s exists)\n", starter_pid_file_default);
}
else
printf("test is NOT running (%s NOT exists)\n", starter_pid_file_default);
unlink(starter_pid_file_default);
return 0;
}
2 运行结果
[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
pid=1016test is already running (/var/run/test.pid exists)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)