#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
阅读(2040) | 评论(0) | 转发(0) |