fork子进程父进程死掉之后,getppid()不为1的解决办法
2024-10-20 11:47:37
代码例子:程序在执行之后,会一直死在while中,打印发现当父进程被终止,getppid() 的值也不为1
pid_t pid;
if((pid = fork()) < 0)
{
printf("fork error\n");
}
else if(pid == 0)
{
while(getppid() != 1)
{
sleep(1);
}
printf("enter clild\n")
}
else
{
exit(0);
}
解释:
在部分版本的linux系统中,负责领养的进程不是init而被替换为systemd进程
1 1105 1105 1105 ? -1 Ss 0 0:01 /lib/systemd/systemd --user
解决办法:
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h> void getPidByName(char* task_name, int *pid)
{
DIR *dir;
struct dirent *ptr;
FILE *fp;
char filepath[50];
char cur_task_name[50];
char buf[1024];
dir = opendir("/proc");
if (NULL != dir)
{
while ((ptr = readdir(dir)) != NULL)
{
if ((strcmp(ptr->d_name, ".") == 0) || (strcmp(ptr->d_name, "..") == 0))
continue;
if (DT_DIR != ptr->d_type)
continue; sprintf(filepath, "/proc/%s/status", ptr->d_name);
fp = fopen(filepath, "r");
if (NULL != fp)
{
if( fgets(buf, 1024-1, fp)== NULL ){
fclose(fp);
continue;
}
sscanf(buf, "%*s %s", cur_task_name);
if (!strcmp(task_name, cur_task_name) && ptr->d_name != 1)
*pid = atoi(ptr->d_name);
fclose(fp);
} }
closedir(dir);
}
}
int main (int argc, char **argv)
{
pid_t pid;
int system_id = 0;
getPidByName("systemd", &system_id);
if(system_id == 0)
{
system_id = 1;
}
if((pid == fork()) < 0)
{
printf("fork child error\n");
}
else if(pid == 0)
{
while(getppid() != systemd_id)
{
sleep(1);
}
printf("enter clind\n");
}
else
{
exit(0);
}
}
最新文章
- Interpolation particles In Katana
- 读取NVRAM中的SN(barcode)
- PHP模拟发送POST请求之一、HTTP协议头部解析
- Qt之QRoundProgressBar(圆形进度条)
- 基础连接已经关闭: 未能为SSL/TLS 安全通道建立信任关系
- 严重: Exception starting filter struts2 --Unable to load configuration
- 在 Visual C++ 中开发自定义的绘图控件
- hdu--3782--找规律--xxx定律
- 阿里云VPS搭建Hexo博客
- Codeforces Round #484 (Div. 2)Cut 'em all!(dfs)
- 前端bug记录
- linux之xxx 不在 sudoers 文件中,此事将被报告(转载)
- “Java是编译执行的语言”这句话对吗?
- Mybatis的针对于同一个有自己父类或子类的递归查询 (如商品分类)
- strace命令,read,write
- 服务链路追踪(Spring Cloud Sleuth)
- jQuery.Form.js 异步提交表单使用总结
- 将DevExpress.Utils.ImageCollection变量的image导出
- 机器学习之路: tensorflow 一个最简单的神经网络
- RedHat Enterprise Linux 6 配置Xmanager ,实现图形界面连接
热门文章
- Android集成mupdf,实现手写笔签字,手指翻页的java代码
- cuda、cudnn、tnesorrt的查看安装
- rtsp协议转换m3u8
- exp1-Password engine-加密API实现与测试
- 软件工程日报八——AlertDiatog的使用
- Centos SSH 免密操作
- CentOS8安装pycharm报错【Can&#39;t connect to X11 window server using &#39;:0&#39; as the value of the DISPLAY variable. 】
- Vue中v-if和v-for一起使用时的优先级
- 升级安装cuda
- Dell CS24-SC 服务器详情