【问题标题】:C program that tells the user which child process finished first告诉用户哪个子进程先完成的 C 程序
【发布时间】:2017-12-05 23:57:21
【问题描述】:

我正在处理一项涉及使用fork 的任务。该程序同时运行两个独立的程序,并告诉用户哪个先完成。如果一个孩子跑完,另一个还在跑的孩子应该立即被杀死。 到目前为止我的代码是这样的......

int main(int argc, char **argv) {

  if (argc != 2) {
    perror("Invalid number of arguments!");
    exit(1);
  }
  pid_t pid;
  pid_t wpid;
  int status = 0;

  for (int i = 0; i < 2; i++) {
    if ((pid = fork()) == 0) {
      execv("/bin/sh", argv[i+1]);
    } 
  }
  while ((wpid = wait(&status)) > 0);
  printf("%s finished first!", <Insert winning program here>);
  return 0;
}

据我了解,这会运行程序,并且在子进程完成之前不会让父进程继续。现在我想知道如何终止另一个孩子并返回获胜过程。

【问题讨论】:

  • errno 中的不确定值调用perror 是一个错误。您可能会收到类似Invalid number of arguments!: SuccessInvalid number of arguments: Not a type-writer 之类的错误消息
  • 你为什么在wait上循环? wait 第一次返回时,它会告诉您刚刚完成的孩子的 pid。最明智的说法是,孩子是第一个完成的。实际上,您可以将“完成”定义为让父进程从进程表中获取子进程的数据,因此根据定义,wait 首先返回的 pid 是首先完成的子进程的 pid。
  • 您的问题是“我怎样才能终止另一个孩子,并返回获胜的过程?”.... 1)在 fork() 之后,“父母”保存了新孩子的 pid。 2)wait会告诉你获胜过程的pid。 3) 使用“kill()”终止“失败”进程。
  • 但是我怎样才能立即获得失败进程的pid以便我可以杀死它?

标签: c process fork


【解决方案1】:

但是我怎样才能立即获得失败进程的 pid 以便我可以杀死它呢?

正如 TonyB 所说:“父母”保存了新孩子的 pid。 2)wait会告诉你获胜进程的pid。更详细:保存两个孩子的PID,等待任何一个,将返回值与(其中一个)保存的PID进行比较;匹配的为赢家,不匹配的为输家。例如:

#define _POSIX_SOURCE
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>

int main(int argc, char **argv)
{
  if (argc != 3)    // with two program arguments, argc is 3
    fputs("Invalid number of arguments!\n", stderr), exit(EXIT_FAILURE);
  pid_t pid[2];     // to store both child pids
  pid_t wpid;
  for (int i = 0; i < 2; i++)
    if ((pid[i] = fork()) == 0)
      execl("/bin/sh", "sh", "-c", argv[i+1], NULL),
      perror(argv[i+1]), exit(EXIT_FAILURE);
  wpid = wait(NULL);                    // wait for first
  int wi = wpid==pid[0] ? 0 : 1;        // get index of winner
  kill(pid[!wi], SIGKILL), wait(NULL);  // kill and reap loser
  printf("%s finished first!\n", argv[wi+1]);
  return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-01
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    • 2013-07-07
    • 1970-01-01
    • 1970-01-01
    • 2011-04-10
    相关资源
    最近更新 更多