父子进程---竞争
                            
                            
                            競爭 fork一個子進程以后,并不知道哪個進程先運行,怎么辦?1.用sleep?當你系統負載很重的時候,你可能sleep很長時間了,可是你想執行的進程依然沒有得到執行2.父進程希望子進程先終止,可以用wait;子進程要等父進程終止,就判斷自己現在的父進程id是不是1,while(getppid()!=1) sleep(1);可是這樣浪費cpu時間,也不能做到有效的競爭
解決辦法:利用進程中的信號機制#include<stdlib.h>
#include<string.h>
#include<fcntl.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/wait.h>
static void charatatime(char *);
int main(void)
{
??pid_t??pid;
??TELL_WAIT();//初始化TELL,WAIT的信號機制
??if ((pid = fork()) < 0)
??{
????err_sys("fork error");
??}
??else if (pid == 0)
??{
???? WAIT_PARENT(); ?//等待父進程先執行
????charatatime("output from child\n");
??}
??else
??{
????charatatime("output from parent\n");
????TELL_CHILD(pid); ? //告訴子進程可以執行了,pid為子進程id號
??}
??exit(0);
}
static void charatatime(char *str)
{
??char??*ptr;
??int????c;
??setbuf(stdout, NULL);??????/* set unbuffered */
??for (ptr = str; (c = *ptr++) != 0; )
????putc(c, stdout);
}結果:output from parentoutput from child這樣就可以自動控制父子進程的執行情況了
 
 
                        
                        
                        解決辦法:利用進程中的信號機制#include<stdlib.h>
#include<string.h>
#include<fcntl.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/wait.h>
static void charatatime(char *);
int main(void)
{
??pid_t??pid;
??TELL_WAIT();//初始化TELL,WAIT的信號機制
??if ((pid = fork()) < 0)
??{
????err_sys("fork error");
??}
??else if (pid == 0)
??{
???? WAIT_PARENT(); ?//等待父進程先執行
????charatatime("output from child\n");
??}
??else
??{
????charatatime("output from parent\n");
????TELL_CHILD(pid); ? //告訴子進程可以執行了,pid為子進程id號
??}
??exit(0);
}
static void charatatime(char *str)
{
??char??*ptr;
??int????c;
??setbuf(stdout, NULL);??????/* set unbuffered */
??for (ptr = str; (c = *ptr++) != 0; )
????putc(c, stdout);
}結果:output from parentoutput from child這樣就可以自動控制父子進程的執行情況了
轉載于:https://blog.51cto.com/nnssll/192870
總結
 
                            
                        - 上一篇: ATEN命令--北大青鸟benet课程
- 下一篇: SEO中HTML标签权重
