我正在嘗試測驗如何使用程式創建和管理行程應該創建行程并執行命令 2 次(每次執行不同的命令)。
我到底想做什么:
- 創建一個新的 PID
- 列印 PID
- 執行命令
- 出口
奇怪的是,當我執行 1 個命令時,它作業正常但是當我執行兩次例程時,第二個命令也被執行了兩次。這意味著執行了 3 個命令。
這是我的代碼:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
void launch_command(char command[]) {
pid_t pid;
pid = fork();
if(pid==0)
{
printf("Creating process %d from %d\n", getpid(),getppid());
system(command);
exit(0);
}
else {
if ((pid = fork()) == -1)
perror("Error while creating a new process");
}
}
int main () {
printf("Root process: %d\n",getpid());
launch_command("/bin/ls -l");
while(wait(NULL) >= 0);
launch_command("/bin/date");
while(wait(NULL) >= 0);
return 0;
}
輸出:
$ ./a.out
Root process: 8924
Creating process 8925 from 8924
Creating process 8928 from 8926
Sun 13 Nov 2022 23:54:51 EST
total 128
-rwxr-xr-x 1 gg staff 49784 13 Nov 23:54 a.out
-rw-r--r-- 1 gg staff 3499 11 Nov 10:59 create_process.c
Creating process 8931 from 8924
Sun 13 Nov 2022 23:54:51 EST
有人可以向我解釋這種行為嗎?
期望的結果應該是:
$ ./a.out
Root process: 8924
Creating process 8925 from 8924
total 128
-rwxr-xr-x 1 gg staff 49784 13 Nov 23:54 a.out
-rw-r--r-- 1 gg staff 3499 11 Nov 10:59 create_process.c
Creating process 8931 from 8924
Sun 13 Nov 2022 23:54:51 EST
uj5u.com熱心網友回復:
正如評論中所指出的,第二次呼叫fork是創建了太多行程。
在第一次呼叫launch_commandreturns 之后,將同時有一個父行程和一個新創建的子行程。它們都將呼叫第二個launch_command函式,生成另外兩個呼叫 的行程,system然后每個行程生成一個額外的行程,同樣從該函式回傳。
將有四個行程執行第二個while回圈。
洗掉第二個fork呼叫,并再次使用相同的值pid來檢查是否失敗。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
void launch_command(const char *command)
{
pid_t pid = fork();
if (0 == pid) {
printf("Creating process %d from %d\n", getpid(), getppid());
system(command);
exit(EXIT_SUCCESS);
} else if (-1 == pid) {
perror("Error while creating a new process");
}
while (wait(NULL) >= 0);
}
int main(void)
{
printf("Root process: %d\n", getpid());
launch_command("/bin/ls -l");
launch_command("/bin/date");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/533767.html
