[英]how waitpid() function is implemented in system() function in linux
我正在經歷Richard Stevens的“UNIX環境中的高級編程”,我找到了這個主題。
* 8.13。 系統功能
*****因為系統是通過調用fork,exec和waitpid實現的,所以有三種類型的返回值。**
1.如果fork失敗或者waitpid返回EINTR以外的錯誤,則系統返回-1並設置errno以指示錯誤。
2.如果exec失敗,暗示shell無法執行,則返回值就好像shell已經執行了exit(127)。
** 3。 否則,所有三個函數 - fork,exec和waitpid-success,以及來自system的返回值是shell的終止狀態,格式為waitpid。******
根據我的理解,我們通過cmdstring名稱 fork()一個進程, exec()使它與父進程分開。
但是無法弄清楚waitpid()函數是如何調用system()函數的 ?
fork()
關閉后,原始進程立即繼續,即fork()
立即返回。 此時,新進程仍在運行。 由於system()
應該是同步的,即必須僅在執行的程序完成后返回,原始程序現在需要在新進程的PID上調用waitpid()
以等待其終止。
在圖片中:
[main process]
.
.
.
fork() [new process]
A
/ \
| \
| \___ exec()
waitpid() .
z .
z . (running)
z .
z Done!
z |
+----<----<---+
|
V
(continue)
在Unix環境中, system()
調用會看起來像這樣:
int system(const char *cmd)
{
int pid = fork();
if(!pid) // We are in the child process.
{
// Ok, so it's more complicated than this, it makes a new string with a
// shell in it, etc.
exec(cmd);
exit(127); // exec failed, return 127. [exec doesn't return unless it failed!]
}
else
{
if (pid < 0)
{
return -1; // Failed to fork!
}
int status;
if (waitpid(pid, &status, 0) > 0)
{
return status;
}
}
return -1;
}
請注意,這是符號system
所做的 - 它有點復雜,因為waitpid
可以提供其他值,以及需要檢查的各種其他事情。
從手冊頁:
system()通過調用/ bin / sh -c命令執行命令中指定的命令,並在命令完成后返回。 在執行命令期間,SIGCHLD將被阻止,SIGINT和SIGQUIT將被忽略。
system()可能使用waitpid()
等待shell命令完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.