你可以用它fork()之後的pid值來判斷
你要宣告一個pid_t結構的變數
接下來就可以使用pid的數值去判斷了
你原來是宣告int pid 因為pid是一個結構化的東西
所以沒辦法用int 去接 一定要使用它的結構形態才可以使用
引用:
#include<sys/types.h>
#include<sys/wait.h>
pid_t wait(int* stat_loc)
|
fork( )有兩個 return 值,大於 0 的是 parent (值不固定),等於 0 的是 child,兩個 process 在 fork( ) 成功後 **同時存在**,並沒有什麼不一樣,可以說是完全一樣的process,fork( ) 之後的parent 與 child 會共同指向 fork() 以下的執行指令,也就是說,parent 和 child 都會執行 fork( ) 以下的程式碼,而且是各自執行,child 會符合 switch 中 pid == 0 的條件、 parent 則會符合 default 中的條件.
可以使用switch來檢驗你有沒有fork()成功
引用:
switch(pid)
{
case -1:
perror("fork failed");
exit(1);
case 0:
Cmessage = "This is the child,";
.
.
break;
default:
Cmessage = "This is the parent";
.
.
break;
}
|
之後再使用if判斷句 就可以達到你要的效果~