Re: 請問...execlp 指令 的意義

看板LinuxDev作者 (Ya-Shiuan)時間18年前 (2007/06/03 11:04), 編輯推噓3(302)
留言5則, 4人參與, 最新討論串2/2 (看更多)
※ 引述《ariesgolem (繼續努力就會成功)》之銘言: : execlp("/bin/ls", ls, NULL); : 請問...當我下這行指令... : 第一個是path...為 /bin/ls : 第二個參數...的 ls 指的是檔名嗎!? 要這麼說也可以.. 你用 C 語言 跑下面簡單的 case #include <stdio.h> int main(int argc, char **argv) { printf("==>%s\n", argv[0]); } 在不同的路徑執行就會有不同的結果 假設我將編譯完檔案放在 /tmp/a.out /$ tmp/a.out ==>tmp/a.out /tmp$ ./a.out ==>./a.out /tmp$ /tmp/a.out ==>/tmp/a.out 一般 shell 都會幫你把「執行的路徑」塞入第一個參數,所以用第一個參數 可以抓到執行時使用的路徑,進而判斷原本執行時的 location 在哪兒 同理,execlp 的第一個參數給的只是慣用性的執行路徑,但沒有一定要給 視呼叫的對象而定,舉個例子. //====================aa.c=================== // aa.c #include <stdlib.h> #include <unistd.h> #include <sys/types.h> int main() { pid_t pid; pid = fork(); if (pid == 0) { execlp("./b.out", NULL); printf("error\n"); exit(-1); } else if (pid < 0) { perror("fork"); exit(1); } pid = fork(); if (pid == 0) { execlp("./b.out", "./b.out", NULL); exit(-1); } else if (pid < 0) { perror("fork"); exit(2); } pid = fork(); if (pid == 0) { execlp("./b.out", "hello", NULL); exit(-1); } else if (pid < 0) { perror("fork"); exit(2); } exit(0); } //====================bb.c=================== //bb.c //gcc bb.c -o b.out #include <stdio.h> #include <unistd.h> #include <sys/types.h> int main(int argc, char **argv) { pid_t pid = getpid(); if (argv[0]) { printf("[%d] => %s\n", pid, argv[0]); } else { printf("[%d] => no argv[0]\n", pid); } } 各編譯成 a.out, b.out 放在同一路徑下執行 a.out [3389] => no argv[0] [3390] => ./b.out [3391] => hello 在第一個 if-else 中,我使用 execlp 並沒有傳入第一個參數,所以得到 第一行結果,b.out 輸出 no argv 的訊息 第二個 if-else 就是常用的作法,得到執行路徑 第三個 if-else 是我惡搞的作法,隨意傳入一個字串,這時在 b.out 輸出 argv[0] 就會得到這字串了... 當然直接執行 b.out 也會得到第二行的結果,因為這是 shell 一般的作法 至於為什麼說看對象而定呢,因為有些程式會看 argv[0] 傳入的字串來決定 內部要什麼的 execution flow 是哪一條,很多系統程式都有這種特性,如 ls -l /usr/bin/reboot /usr/bin/poweroff lrwxrwxrwx 1 root root 13 12月 29 01:48 /usr/bin/poweroff -> consolehelper lrwxrwxrwx 1 root root 13 12月 29 01:48 /usr/bin/reboot -> consolehelper 一般情況 reboot, poweroff 系統會有不同的行為出現,但都是同一隻程式 所為,大概就是利用這方法吧 此外有些程式也會利用 argv[0] 來檢查有沒有被惡搞.. -- 有錯誤請多指教.. thanks a lot -- -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.113.214.90 ※ 編輯: andytzeng 來自: 140.113.214.90 (06/03 11:06)

06/03 21:19, , 1F
感謝回應 感謝回應
06/03 21:19, 1F

06/03 22:20, , 2F
good....good...
06/03 22:20, 2F

06/04 23:07, , 3F
嗯,symbolic link 的 busybox 也是一例...
06/04 23:07, 3F

06/05 09:03, , 4F
耶..對耶...竟然忘記 busybox 這超有名的例子..
06/05 09:03, 4F

06/05 09:03, , 5F
感謝 y 大點醒
06/05 09:03, 5F
文章代碼(AID): #16OY_KuJ (LinuxDev)
討論串 (同標題文章)
文章代碼(AID): #16OY_KuJ (LinuxDev)