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);
      }
    }
  • 相关阅读:
    Codeforces 798C. Mike and gcd problem 模拟构造 数组gcd大于1
    Codeforces 796C. Bank Hacking
    Codeforces 792B. Counting-out Rhyme
    gym 101164 H.Pub crawl 凸包
    hdu 6053 TrickGCD 筛法
    hdu 6041 I Curse Myself 无向图找环+优先队列
    bzoj 2243: [SDOI2011]染色 线段树区间合并+树链剖分
    codeforces gym 101164 K Cutting 字符串hash
    树链剖分求lca
    UESTC 1697 简单GCD问题(一) 筛法
  • 原文地址:https://www.cnblogs.com/Ansing/p/11540516.html
Copyright © 2011-2022 走看看