进程
一、网址参考
二、实践
1、进程创建
1 shell = get_shell_name(); 2 if(!shell) 3 return -1; 4 5 child = vfork(); 6 if(child < 0) 7 return -1; 8 9 if(child == 0) { 10 execle(shell, shell, "-c", str, (char *)NULL, NULL); 11 _exit(127); 12 } 13 14 if(SYS_NOBLOCK == proctrl->blk) 15 ret = safe_waitpid(child, &status, WNOHANG); 16 else 17 ret = safe_waitpid(child, &status, 0); 18 19 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { 20 return -1; 21 }
2、进程终止
if(!proctrl) return -1; if(proctrl->child < 0) return -1; ret = kill(proctrl->child, SIGTERM);
进程有可能没有真正被终止,需要加判断:
通过进程的pid编号判断进程是否存在,主要是查看/proc中是否存在pid编号的文件夹:
int check_dir_exist(const char *dir_path) { DIR *dir = NULL; int ret = -1; if(!dir_path) return -1; dir = opendir(dir_path); if(dir) { ret = 0; closedir(dir); } return ret; }
int check_process_with_pid_num(int pid) { char pid_dir[64]; if(pid <= 0) return -1; memset(pid_dir, 0, sizeof(pid_dir)); snprintf(pid_dir, sizeof(pid_dir)-1, "/proc/%d", pid); return check_dir_exist(pid_dir); }