Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1058384
  • 博文数量: 573
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 66
  • 用 户 组: 普通用户
  • 注册时间: 2016-06-28 16:21
文章分类

全部博文(573)

文章存档

2018年(3)

2016年(48)

2015年(522)

分类: LINUX

2015-12-23 14:54:43


#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(= 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
阅读(377) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~