代码例子:程序在执行之后,会一直死在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);
  }
}

最新文章

  1. Interpolation particles In Katana
  2. 读取NVRAM中的SN(barcode)
  3. PHP模拟发送POST请求之一、HTTP协议头部解析
  4. Qt之QRoundProgressBar(圆形进度条)
  5. 基础连接已经关闭: 未能为SSL/TLS 安全通道建立信任关系
  6. 严重: Exception starting filter struts2 --Unable to load configuration
  7. 在 Visual C++ 中开发自定义的绘图控件
  8. hdu--3782--找规律--xxx定律
  9. 阿里云VPS搭建Hexo博客
  10. Codeforces Round #484 (Div. 2)Cut 'em all!(dfs)
  11. 前端bug记录
  12. linux之xxx 不在 sudoers 文件中,此事将被报告(转载)
  13. “Java是编译执行的语言”这句话对吗?
  14. Mybatis的针对于同一个有自己父类或子类的递归查询 (如商品分类)
  15. strace命令,read,write
  16. 服务链路追踪(Spring Cloud Sleuth)
  17. jQuery.Form.js 异步提交表单使用总结
  18. 将DevExpress.Utils.ImageCollection变量的image导出
  19. 机器学习之路: tensorflow 一个最简单的神经网络
  20. RedHat Enterprise Linux 6 配置Xmanager ,实现图形界面连接

热门文章

  1. Android集成mupdf,实现手写笔签字,手指翻页的java代码
  2. cuda、cudnn、tnesorrt的查看安装
  3. rtsp协议转换m3u8
  4. exp1-Password engine-加密API实现与测试
  5. 软件工程日报八——AlertDiatog的使用
  6. Centos SSH 免密操作
  7. CentOS8安装pycharm报错【Can&#39;t connect to X11 window server using &#39;:0&#39; as the value of the DISPLAY variable. 】
  8. Vue中v-if和v-for一起使用时的优先级
  9. 升级安装cuda
  10. Dell CS24-SC 服务器详情