/* standard_pipe.c */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#define BUFSIZE 1024
int main()
{
FILE *fp;
char *cmd = "ps -ef";
char buf[BUFSIZE];
/*调用popen函数执行相应的命令*/
if ((fp = popen(cmd, "r")) == NULL)
{
printf("Popen error\n");
exit(1);
}
while ((fgets(buf, BUFSIZE, fp)) != NULL)
{
printf("%s",buf);
}
pclose(fp);
exit(0);
}
结果:
lsb@ubuntu:~/gx/wangluo$ ./signal
Waiting for signal SIGINT or SIGQUIT...
^C 按下ctrl+c 打印如下:
I have get SIGINT
*****************************************************
#include <sys/wait.h>
#include <unistd.h>
int main()
{
pid_t pid;
int ret;
/* 创建一子进程 */
if ((pid = fork()) < 0)
{
printf("Fork error\n");
exit(1);
}
if (pid == 0)
{
/* 在子进程中使用raise函数发出SIGSTOP信号,使子进程暂停 */
printf("Child(pid : %d) is waiting for any signal\n", getpid());
raise(SIGSTOP);
exit(0);
}
else
{
/* 在父进程中收集子进程发出的信号,并调用kill函数进行相应的操作 */
if ((waitpid(pid, NULL, WNOHANG)) == 0)
{
if ((ret = kill(pid, SIGKILL)) == 0)
{
printf("Parent kill %d\n",pid);
}
else
{
printf("Parent kill error\n");
}
}
waitpid(pid, NULL, 0);
exit(0);
}
}
结果:
lsb@ubuntu:~/gx/wangluo$ ./kill_raise
Parent kill 4354
**************************************************
信号的封装
/* sigset.c */
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
/*自定义的信号处理函数*/
void my_func(int signum)
{
printf("If you want to quit,please try SIGQUIT\n");
}
int main()
{
sigset_t set,pendset;
struct sigaction action1,action2;
/* 初始化信号集为空 */
if (sigemptyset(&set) < 0)
{
perror("sigemptyset");
exit(1);
}
/* 将相应的信号加入信号集 */
if (sigaddset(&set, SIGQUIT) < 0)//等于set=[SIGQIUT]一个数组
{
perror("sigaddset");
exit(1);
}
if (sigaddset(&set, SIGINT) < 0)
{
perror("sigaddset");
exit(1);
}
//安装信号处理句柄
if (sigismember(&set, SIGINT))
{
sigemptyset(&action1.sa_mask);
action1.sa_handler = my_func;
action1.sa_flags = 0;
sigaction(SIGINT, &action1, NULL);
}
if (sigismember(&set, SIGQUIT))
{
sigemptyset(&action2.sa_mask);
action2.sa_handler = SIG_DFL;
action2.sa_flags = 0;
sigaction(SIGQUIT, &action2,NULL);
}
/* 设置信号集屏蔽字,此时set中的信号不会被传递给进程,暂时进入待处理状态 */
if (sigprocmask(SIG_BLOCK, &set, NULL) < 0)
{
perror("sigprocmask");
exit(1);
}
else
{
printf("Signal set was blocked, Press any key!");
getchar();
}
/* 在信号屏蔽字中删除set中的信号 */
if (sigprocmask(SIG_UNBLOCK, &set, NULL) < 0)
{
perror("sigprocmask");
exit(1);
}
else
{
printf("Signal set is in unblock state\n");
}
while(1);
exit(0);
}