父进程干掉子进程

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <ctype.h>

#define MAX_CHILD_NUMBER 10
#define SLEEP_INTERVAL 1

int proc_number=0;
void do_something();
main(int argc, char* argv[])
{
    int child_proc_number = MAX_CHILD_NUMBER;
    int i, ch;
    pid_t child_pid;
    pid_t pid[10]={0};
    if (argc > 1)
    {
        child_proc_number = atoi(argv[1]);
        child_proc_number
            = (child_proc_number > 10) ? 10 : child_proc_number;
    }
      for (i=0; i<child_proc_number; i++)
    {
        child_pid = fork();
        if(child_pid == -1)
        {
            perror("Creat error\n");
            return -1;
        } else if(child_pid > 0) {
            pid[i] = child_pid;
        } else {
            proc_number = i;
            do_something(getpid());
        }
    }
    for(i = 0; i < child_proc_number; i++) {
        fflush(stdin);
        scanf("%d", &ch);
        kill(pid[i], SIGKILL);
    }
    return 0;
}
void do_something(pid_t pid)
{
    for(;;)
    {
        printf("This is process pid\t%u.\tNO.\t%d\n", pid, proc_number);
        sleep(SLEEP_INTERVAL);
    }
}

上述是一个代码实例。
int kill(pid_t pid, int sig)
其中的pid表示要干掉的子进程的pid号,sig表示kill的级别,我理解的是要干掉的强度。

如果你想中止一个进程时,直接输入它的编号,敲回车就行了。
一个运行结果:


This is process pid    3278.    NO.    0
This is process pid    3279.    NO.    1
This is process pid    3281.    NO.    3
This is process pid    3280.    NO.    2
This is process pid    3278.    NO.    0
This is process pid    3279.    NO.    1
This is process pid    3281.    NO.    3
This is process pid    3280.    NO.    2
0
This is process pid    3279.    NO.    1
This is process pid    3281.    NO.    3
This is process pid    3280.    NO.    2
This is process pid    3279.    NO.    1
This is process pid    3281.    NO.    3
This is process pid    3280.    NO.    2
2
This is process pid    3281.    NO.    3
This is process pid    3280.    NO.    2
This is process pid    3281.    NO.    3
This is process pid    3280.    NO.    2
This is process pid    3281.    NO.    3
This is process pid    3280.    NO.    2
1
This is process pid    3281.    NO.    3
This is process pid    3281.    NO.    3
This is process pid    3281.    NO.    3
3

<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>
阅读(851) | 评论(0) | 转发(0) |
0

上一篇:信号灯

下一篇:用c语言模拟进程调度

给主人留下些什么吧!~~
评论热议
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值