linux啟動新程序執行二進位制檔案
阿新 • • 發佈:2018-12-22
在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; }