[code小心得]C system API 實做

大家好  小弟又來嘴砲了

主要利用fork 和 execl 來達到實做,不過有個問題。如果是把指令寫在im_system上的話,執行結果是 出現 no sush file 的訊息,但用script的方式ok。
這點是比較弔詭的地方,另外  一般system API 是有幫你做wait的行為(當然也會對效能造成影響,但相對幫助系統穩定),所以自己在實做時   似乎得把這點列入考量

#include <"stdio.h"> #include <"sys/wait.h"> #include <"unistd.h"> int im_system(const char * cmdstring) { pid_t pid; int status; if(cmdstring == NULL) //if cmdstring is NULL,then return 1 return 1; pid = fork(); //create a child thread. if(pid < 0){ status = -1; }else if(pid == 0){ execl("/bin/sh", "sh", "-C", cmdstring, NULL); /*Use shell to exec cmd, if exec fail exit return 127 */ _exit(127); } if(waitpid(pid, &status, 0) == -1) //wait function error,drop not use status status = -1; return status; //return status } int main(void) { int result; result = im_system("showfile.sh"); printf("exec result = %d\n", result); return 0; }
以上下台一鞠躬  感謝收看

留言