在linux系统中,我们有时需要通过在程序中启动其他二进制文件,使其运行在独立的进程当中。我们可以通过exec函数族来进行新的文件的执行。在这个过程中,我们需要注意僵尸进程的出现。避免僵尸进程可以有多种方法,例如通过信号,或者连续开启2个进程等等。我们此处通过连续创建子进程来规避僵尸进程的问题。
通过新进程运行二进制文件
#include <stdio.h>
#include <unistd.h>
#define OK 0UL
#define ERR 1UL
ULONG create_new_process(char *file_path, char *file_name){
int status = 0;
if(file_path == NULL || file_name == NULL)
return ERR;
pid_t pid;
pid = vfork();
if(pid < 0){
return ERR;
}
else if(pid == 0){
pid = vfork();
if(pid < 0)
_exit(1);
if(pid == 0){
if(execl(file_path, file_name, (char*) 0) == -1){
printf("start the %s failed \r\n", file_path);
_exit(1);
}
printf("start the %s success \r\n",file_path);
_exit(0);
}
sleep(2);
if(waitpid(pid, &status, WNOHANG) != pid){
_exit(0);
}else{
if(WIFEXITED(status)){
if(WEXITSTATUS(status) == 0){
_exit(0);
}else{
_exit(1);
}
}
_exit(1);
}
}
if(waitpid(pid, &status, 0) != pid){
pirntf("wiatpid error %d \r\n", pid);
return ERR;
}
if(WIFEXITED(status)){
if(WEXITSTATUS(status) == 0)
return OK;
}
return ERR;
}