linux訊號處理--通過發送訊號控制進程,linux訊號處理
要求:
實現兩個程式mysignal、mycontrl, mycontrl給mysignal發送SIGINT訊號,控制mysiganl是否在螢幕列印"hello,world"字串.
//makefile
.SUFFIXES: .c .oCC=gccSRCS1=mysignal.cSRCS2=mycontrol.c OBJS1=$(SRCS1:.c=.o)OBJS2=$(SRCS2:.c=.o)EXEC1=mysignalEXEC2=mycontrolall: $(OBJS1) $(OBJS2) $(CC) -o $(EXEC1) $(OBJS1) $(CC) -o $(EXEC2) $(OBJS2) @echo '-------------ok--------------'.c.o: $(CC) -g -o $@ -c $< clean: rm -f $(OBJS1) $(OBJS2) rm -f core*
//mysignal.c
#include <stdio.h>#include <stdlib.h>#include <signal.h>int status = 0;//全域量,1-列印,0-不列印void catch_Signal(int Sign){ switch (Sign) { case SIGINT: if (status == 0) { status = 1; } else { status = 0; } }}int signal1(int signo, void(*func)(int)){ struct sigaction act, oact; act.sa_handler = func; sigemptyset(&act.sa_mask); act.sa_flags = 0; return sigaction(signo, &act, &oact);}int main(int arg, char *args[]){ signal1(SIGINT, catch_Signal);//捕捉SIGINT訊號 while (1) { if (status)//如果status為1,列印字串”hello“ { puts("hello, world"); } sleep(1); } return 0;}
//mycontrol.c
#include <stdio.h>#include <stdlib.h>#include <signal.h>int main(int arg, char *args[]){ if (arg < 2)//如果沒有參數,main返回 { return -1; } else { int pid = atoi(args[1]); kill(pid, SIGINT);//向指定的pid發送SIGINT訊號 } return 0;}
運行效果: