要求:
实现两个程序mysignal、mycontrl, mycontrl给mysignal发送SIGINT信号,控制mysiganl是否在屏幕打印"hello,world"字符串.
//makefile
.SUFFIXES: .c .o
CC=gcc
SRCS1=mysignal.c
SRCS2=mycontrol.c
OBJS1=$(SRCS1:.c=.o)
OBJS2=$(SRCS2:.c=.o)
EXEC1=mysignal
EXEC2=mycontrol
all: $(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;
}
运行效果:
本文永久更新地址://m.ajphoenix.com/linux/22061.html