zoukankan      html  css  js  c++  java
  • fork子进程父进程死掉之后,getppid()不为1的解决办法

    代码例子:程序在执行之后,会一直死在while中,打印发现当父进程被终止,getppid() 的值也不为1  

    pid_t pid;

    if((pid = fork()) < 0)
    {
      printf("fork error ");
    }
    else if(pid == 0)
    {
      while(getppid() != 1)
      {
        sleep(1);
      }

      printf("enter clild ")
    }
    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 ");
      }
      else if(pid == 0)
      {
        while(getppid() != systemd_id)
        {
          sleep(1);
        }
        printf("enter clind ");
      }
      else
      {
        exit(0);
      }
    }
  • 相关阅读:
    面试口试技巧
    windbg+psscor2查看方法源代码
    用UIScrollView做一个支持两点触控缩放图片
    vs2008使用过AnkhSVN后不能绑定到vss的问题解决
    IOS开发之手势——UIGestureRecognizer 共存(转)
    windbg创建dump文件
    面向.NET开发人员的WinDbg入门教程(转)
    Vector:no such file or directory解决
    .net调试插件sosex的mk命令显示调用堆栈
    NSString 中包含中文字符时转换为NSURL
  • 原文地址:https://www.cnblogs.com/Ansing/p/11540516.html
Copyright © 2011-2022 走看看