fork子进程父进程死掉之后,getppid()不为1的解决办法

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

#include

#include

#include

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); }}

Top