我想知道是否有某种方法可以从孩子那里获取while语句(printf("Death of child: %d with exit code %d\n",i, WEXITSTATUS(status));
)整数i
的内部。
我正在从execlp
获取输出(此程序内部有一个超时,该超时返回一个随机数),但是我想获取哪个是每个返回响应的标识i
。 / p>
int main (int argc, char *argv[])
{
int i;
int pid;
int status;
int pro= atoi (argv[argc - 1]);
char programName[] = "./child";
if (argc < 2 || argc > 2){
printf("Only one argument is allowed\n");
exit (0);
}
for (i = 0; i < pro; i++)
{
pid = fork();
if(pid == 0)
{
printf("Created child %d with pid=%d\n",i, getpid());
char child[10];
snprintf(child, 10, "%d", i);
if (execlp(programName, programName, child, NULL) < 0){
printf("Error running: %s\n",programName);
}
exit(2);
}
}
while(wait(&status)>0)
{
if ( WIFEXITED(status) ){
printf("Death of child: %d with timeout %d\n",i, WEXITSTATUS(status));
if (WEXITSTATUS(status) > 5)
{
printf("Time exceeded\n");
}
}
}
exit (0);
}
也许我的方法不正确。欢迎任何提示。我是c的新手。
答案 0 :(得分:2)
wait
将返回已更改过程的pid。要将其映射回i
,请将从fork
返回的所有pid保存到表中,并作为查找参考。
pid_t table[pro] = {0};
pid_t child=0;
for (i = 0; i < pro; i++)
{
pid = fork();
if(pid == 0)
{
printf("Created child %d with pid=%d\n",i, getpid());
char child[10];
snprintf(child, 10, "%d", i);
if (execlp(programName, programName, child, NULL) < 0){
printf("Error running: %s\n",programName);
}
exit(2);
}
else
{
table[i] = pid;
}
}
while((child=wait(&status)) > 0)
{
if ( WIFEXITED(status) ){
i = -1;
for (int j = 0; j < pro; j++)
{
if (table[j] == child))
{
i = j;
break;
}
}
printf("Death of child: %d with timeout %d\n",i, WEXITSTATUS(status));