進程間通信之: 信號量
現在我們調用這些簡單易用的接口,可以輕松解決控制兩個進程之間的執行順序的同步問題。實現代碼如下所示:
/*fork.c*/
#includesys/types.h>
#includeunistd.h>
#includestdio.h>
#includestdlib.h>
#includesys/types.h>
#includesys/ipc.h>
#includesys/shm.h>
#defineDELAY_TIME3/*為了突出演示效果,等待幾秒鐘,*/
intmain(void)
{
pid_tresult;
intsem_id;
sem_id=semget(ftok(.,'a'),1,0666|IPC_CREAT);/*創建一個信號量*/
init_sem(sem_id,0);
/*調用fork()函數*/
result=fork();
if(result==-1)
{
perror(Forkn);
}
elseif(result==0)/*返回值為0代表子進程*/
{
printf(Childprocesswillwaitforsomeseconds...n);
sleep(DELAY_TIME);
printf(Thereturnedvalueis%dinthechildprocess(PID=%d)n,
result,getpid());
sem_v(sem_id);
}
else/*返回值大于0代表父進程*/
{
sem_p(sem_id);
printf(Thereturnedvalueis%dinthefatherprocess(PID=%d)n,
result,getpid());
sem_v(sem_id);
del_sem(sem_id);
}
exit(0);
}
讀者可以先從該程序中刪除掉信號量相關的代碼部分并觀察運行結果。
$./simple_fork
Childprocesswillwaitforsomeseconds…/*子進程在運行中*/
Thereturnedvalueis4185inthefatherprocess(PID=4184)/*父進程先結束*/
[…]$Thereturnedvalueis0inthechildprocess(PID=4185)/*子進程后結束了*/
再添加信號量的控制部分并運行結果。
$./sem_fork
Childprocesswillwaitforsomeseconds…
/*子進程在運行中,父進程在等待子進程結束*/
Thereturnedvalueis0inthechildprocess(PID=4185)/*子進程結束了*/
Thereturnedvalueis4185inthefatherprocess(PID=4184)/*父進程結束*/
本實例說明使用信號量怎么解決多進程之間存在的同步問題。我們將在后面講述的共享內存和消息隊列的實例中,看到使用信號量實現多進程之間的互斥。
linux操作系統文章專題:linux操作系統詳解(linux不再難懂)數字通信相關文章:數字通信原理
評論