父子进程---竞争
競(jìng)爭(zhēng) fork一個(gè)子進(jìn)程以后,并不知道哪個(gè)進(jìn)程先運(yùn)行,怎么辦?1.用sleep?當(dāng)你系統(tǒng)負(fù)載很重的時(shí)候,你可能sleep很長(zhǎng)時(shí)間了,可是你想執(zhí)行的進(jìn)程依然沒有得到執(zhí)行2.父進(jìn)程希望子進(jìn)程先終止,可以用wait;子進(jìn)程要等父進(jìn)程終止,就判斷自己現(xiàn)在的父進(jìn)程id是不是1,while(getppid()!=1) sleep(1);可是這樣浪費(fèi)cpu時(shí)間,也不能做到有效的競(jìng)爭(zhēng)
解決辦法:利用進(jìn)程中的信號(hào)機(jī)制#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的信號(hào)機(jī)制
??if ((pid = fork()) < 0)
??{
????err_sys("fork error");
??}
??else if (pid == 0)
??{
???? WAIT_PARENT(); ?//等待父進(jìn)程先執(zhí)行
????charatatime("output from child\n");
??}
??else
??{
????charatatime("output from parent\n");
????TELL_CHILD(pid); ? //告訴子進(jìn)程可以執(zhí)行了,pid為子進(jìn)程id號(hào)
??}
??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);
}結(jié)果:output from parentoutput from child這樣就可以自動(dòng)控制父子進(jìn)程的執(zhí)行情況了
解決辦法:利用進(jìn)程中的信號(hào)機(jī)制#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的信號(hào)機(jī)制
??if ((pid = fork()) < 0)
??{
????err_sys("fork error");
??}
??else if (pid == 0)
??{
???? WAIT_PARENT(); ?//等待父進(jìn)程先執(zhí)行
????charatatime("output from child\n");
??}
??else
??{
????charatatime("output from parent\n");
????TELL_CHILD(pid); ? //告訴子進(jìn)程可以執(zhí)行了,pid為子進(jìn)程id號(hào)
??}
??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);
}結(jié)果:output from parentoutput from child這樣就可以自動(dòng)控制父子進(jìn)程的執(zhí)行情況了
轉(zhuǎn)載于:https://blog.51cto.com/nnssll/192870
總結(jié)
- 上一篇: ATEN命令--北大青鸟benet课程
- 下一篇: 由DWR1.0到DWR2.0常出现的问题