A successful man is one who can lay a firm foundation with the bricks others have thrown at him.--------成功的人會利用別人丟他的磚頭來建構一個堅固的基礎。
1, Linux下信號概念以及如何安裝信號
小黑寫過相關的博客,可以移步:
https://blog.csdn.net/weixin_46027505/article/details/104530022
2, 多進程回顧
下面是多進程編程以及進程的博客。需要了解的可以看看:
https://blog.csdn.net/weixin_46027505/article/details/105141592
https://blog.csdn.net/weixin_46027505/article/details/104812719
3, 如何利用信號實現進程間通信
下面我們用一段代碼完成下面這樣一件事情:
我爸爸就是父進程,小黑我就是子進程。
然後有一天,爸爸下班回家了,但是沒帶鑰匙,然後急着上廁所,就一直在那裏敲門,其實門是開着的,他卻不試試開門,(這個就代表父進程阻塞在外面,無法進入家上廁所)
而這個時候不巧的事情,小黑我卻在聽音樂(代表子進程想幹自己的事情),然後終於我聽完了一首歌,聽到了父親急切的敲門聲,我就大聲喊了一聲,“門是開着的”(就是給父進程發個信號)
終於爸爸衝向了廁所,把門鎖了,
這時候小黑也很慘,也想上廁所了,就不斷敲廁所門,催爸爸快點上完,這是就是子進程阻塞着,直到爸爸和我說上完了,我可以上廁所了(爸爸給我發的信號),
然後爸爸打算帶我去shopping,就等着我上完廁所,
最後故事結束。
下面我們實現代碼:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
int wc_door = 0; //廁所門關着的意思
int home_door = 0; //爸爸以爲家裏的門是關着的
//爸爸上完廁所後告訴兒子上完了,小黑就知道廁所的門可以開了
void sig_child(int sig_num)
{
if( SIGUSR1 == sig_num )
{
wc_door = 1;
}
}
//小黑告訴爸爸門是開着的,爸爸就知道門可以開了
void sig_parent(int sig_num)
{
if( SIGUSR2 == sig_num )
{
home_door = 1;
}
}
int main(int argc, char *argv[])
{
int pid;
int wstatus;
signal(SIGUSR1, sig_child);
signal(SIGUSR2, sig_parent);
if( (pid=fork()) < 0 )
{
printf("Create child process failure: %s\n", strerror(errno));
return -2;
}
//下面是子進程空間
else if(pid == 0)
{
printf("xiaohei is listening to music\n");
sleep(5);//聽歌5分鐘,沒有聽到爸爸敲門
printf("xiaohei finish listen music and tell father door is open\n");//聽完
kill(getppid(), SIGUSR2); //大聲喊,告訴爸爸門是開着的
sleep(3);
while( !wc_door )
{
printf("xiaohei ask father to la baba quickly\n");
sleep(1);
}
printf("xiaohei finish la baba\n");
return 0;
}
//下面是父進程空間
printf("father start knock the door\n"); //爸爸開始敲門
while( !home_door ) //但是不知道門是開着的就一直敲
{
sleep(1);
}
//聽到小黑的聲音,然後開門上廁所
printf("father start running to WC and la xiang\n");
sleep(10); //上廁所的時間
printf("father tell xiaohei can come in wc\n");//告訴小黑自己上完了
kill(pid, SIGUSR1); ![在這裏插入圖片描述](https://img-blog.csdnimg.cn/20200327150910227.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NjAyNzUwNQ==,size_16,color_FFFFFF,t_70#pic_center)
printf("father wait me to go to shopping\n");
wait(&wstatus);
printf("story over and we go to shopping\n");
return 0;
}
這就完成了父子進程間同步的問題了。