【发布时间】:2014-02-01 10:53:48
【问题描述】:
我已经完成了一个 C 程序,它产生了许多进程,然后在短时间内杀死它们。我对此并不陌生,并试图弄清楚为什么我试图跟踪我的进程以杀死工作的方式。我的指针 pid_t* id 指向创建时 cmd 行参数要求的进程 ID 的数量。
现在这是我的难题。 fork() 为子级和父级返回一个值,但我找不到关于它如何工作的固定顺序。它是先返回子值还是父值,还是未定义?
id[] 数组对于每个生成的进程都是相同的,对吧(因为没有生成 n_child 数组)?
由于程序 100% 的时间都在工作,因此似乎总是最后返回父级,因为这是在终止过程中存储在数组中的内容。这是否是跟踪流程的“安全”方式(请记住,我不是在寻找最好的方式或任何东西,因为我确信有很多更好的方式)?似乎答案应该是否定的,并且我应该只在确定它是父数组时才设置数组。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#define MAX_N_CHILD 10
int main (int argc, char **argv) {
int n_child, i;
pid_t* id;
/* note: on a 32 bit machine, pid_t is defined as the __S32_TYPE,
which is an int rather than a long */
if (argc == 2) {
n_child = atoi (argv[1]); /* captures the command line argument */
/* **NOTE** argv[0] is always the file name of this program */
if (n_child > MAX_N_CHILD) {
printf ("Too many children wanted!\n");
return 0;
}
}
else {
printf ("Invalid number of arguments!\n");
return 0;
}
id = malloc( sizeof(pid_t) * n_child );
if(id == NULL)
{
return 0;
}
printf ("******** HELLO! *********\n");
printf ("parent %d(CPU#%d)\n", getpid(), sched_getcpu());
/* create new process(es) */
for(i = 0; i < n_child; ++i)
{
id[i] = fork();
if (id[i] == -1)
{
printf("Error: Process not created");
return 0;
}
else if (id[i] == 0) { /* I'm the child */
//execlp ("./dummy", "dummy", NULL); /* replace myself with a new program */
sleep(2);
}
else
{
continue; //Continue loop
}
} //End for
/* Only the parent process should get here. */
/* wait a little to let the child processes run before killing them */
usleep(50000); /* sleep for 50000 microseconds */
/* kill */
for(i = 0; i < n_child; ++i)
{
printf ("killing %d\n", id[i]);
kill (id[i], SIGKILL); /* SIGKILL is defined in signal.h */
}
//pkill -TERM -P id //Only kills immediate children of parent
printf ("All %d child processes killed!\n", n_child);
}
【问题讨论】: