Demo entry 6327959

exp1

   

Submitted by anonymous on Nov 25, 2016 at 09:36
Language: C. Code size: 1.5 kB.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <time.h>

void parent();
void child1();
void child2();
void sigdeal(int sig_no);

static int pipefd[2];
static int p1,p2;
static char msg1[50],msg2[50];

/*
 主程序体,功能如下
 1.设置软中断信号SIGINT
 2.创建子进程p1、p2
 3.等待子进程p1、p2退出
 4.关闭管道
 */
int main()
{
    pipe(pipefd);
    signal(SIGINT,parent);
    p1=fork();
    if(p1==0)
        child1();
    p2=fork();
    if(p2==0)
        child2();
    wait(0);
    wait(0);
    close(pipefd[1]);
    close(pipefd[0]);
    printf("Parent Process is Killed!\n");
    kill(getpid(),SIGINT);
    return 0;
}

/*父进程信号处理*/
void parent()
{
    kill(p1,SIGUSR1);
    kill(p2,SIGUSR2);
}

/*
 子进程p1功能如下
 1.设置忽略信号SIGINT
 2.设置信号SIGUSR1
 3.发送数据至无名管道
 */
void child1()
{
    int i=1;
    signal(SIGINT,SIG_IGN);
    signal(SIGUSR1,sigdeal);
    while(1){
        sprintf(msg1,"I send you %d times.",i);
        write(pipefd[1],msg1,50);
        i++;
        sleep(1);
    }
}

/*
 子进程p2功能如下
 1.设置忽略信号SIGINT
 2.设置信号SIGUSR2
 3.接收并显示管道数据
 */
void child2()
{
    signal(SIGINT,SIG_IGN);
    signal(SIGUSR2,sigdeal);
    while(1){
        read(pipefd[0],msg2,50);
        printf("%s\n",msg2);
    }
}

/*
 信号处理子程序功能如下
 1.显示退出信息
 2.退出
 */
void sigdeal(int sig_no)
{
    if(sig_no==SIGUSR1)
        printf("Child Process 1 is Killes by Parent!\n");
    if(sig_no==SIGUSR2)
        printf("\nChild Process 2 is Killed by Parent!\n");
    exit(0);
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).