C中的分叉和过程

时间:2017-12-06 03:00:54

标签: c process signals fork

我应该编写一个程序,在两个独立的进程中运行两个脚本,然后返回哪一个先完成。不幸的是,我的程序返回了较慢的进程,这让我很困惑。我确保pids不是0,因此它们不是子进程。然后我将每个进程的pid与首先完成的进程的pid进行比较,但由于某种原因,较慢的程序被打印出来。

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

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

  if (argc != 3) {
    printf("Invalid number of arguments!");
    exit(1);
  }
  pid_t one;
  pid_t two;
  int status = 0;
  pid_t winner;

  char const *args[] = {"/bin/sh", argv[1], argv[2], NULL};

  if ((one = fork()) == 0) {
    printf("%s is starting.\n",argv[1]);
    execv(args[0], args[1]);
  }
  if ((two = fork()) == 0 && (one != 0)) {
    printf("%s is starting\n",argv[2]);
    execv(args[0], args[2]);
  }
  if (one != 0 && two != 0) {
    winner = wait(&status);
    if (winner == -1) {
      if (one == winner) {
    kill(one, SIGKILL);
    printf("%s wins by default!\n", argv[2]);
      }
      else if (two == winner) {
    kill(two, SIGKILL);
    printf("%s wins by default!\n", argv[1]);
      }
    }
    else {
      if (one == winner) {
    kill(two, SIGKILL);
    printf("%s is finished!\n", argv[1]);
    printf("%s is the winner\n", argv[1]);
      }
      if (two == winner) {
    kill(one, SIGKILL);
    printf("%s is finished!\n", argv[2]);
    printf("%s is the winner\n", argv[2]);
      }
    }
  }
  return 0;
}

0 个答案:

没有答案