summaryrefslogtreecommitdiffstats
path: root/os_win32/runcmd.c
blob: 026171726139bbae7bb89645bfcae5bc8e5d3177 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
 * Run console command and wait for user input
 *
 * Home page of code is: http://www.smartmontools.org
 *
 * Copyright (C) 2011 Christian Franke
 *
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

char svnid[] = "$Id: runcmd.c 4760 2018-08-19 18:45:53Z chrfranke $";

#include <stdio.h>
#include <windows.h>

int main(int argc, char **argv)
{
  char * cmd = GetCommandLineA();
  DWORD exitcode;
  STARTUPINFOA si = { sizeof(si), };
  PROCESS_INFORMATION pi;
  int key;

  if (*cmd == '"') {
    cmd++;
    while (*cmd && !(*cmd == '"' && cmd[-1] != '\\'))
      cmd++;
    if (*cmd)
      cmd++;
  }
  else {
    while (*cmd && !(*cmd == ' ' || *cmd == '\t'))
      cmd++;
  }

  while (*cmd == ' ' || *cmd == '\t')
    cmd++;

  if (*cmd) {
    printf("%s\n\n", cmd); fflush(stdout);
  }

  if (!*cmd) {
    printf("Usage: %s COMMAND [ARG ...]\n", argv[0]);
    exitcode = 1;
  }
  else if (!CreateProcessA((char *)0, cmd,
      (SECURITY_ATTRIBUTES *)0, (SECURITY_ATTRIBUTES *)0,
      TRUE/*inherit*/, 0/*no flags*/, (void *)0, (char *)0, &si, &pi)
  ) {
    DWORD err = GetLastError();
    if (err == ERROR_FILE_NOT_FOUND)
      printf("Command not found\n");
    else
      printf("CreateProcess() failed with error=%u\n", err);
    exitcode = 1;
  }
  else {
    CloseHandle(pi.hThread);

    exitcode = 42;
    WaitForSingleObject(pi.hProcess, INFINITE);
    GetExitCodeProcess(pi.hProcess, &exitcode);
    CloseHandle(pi.hProcess);

    if (exitcode)
      printf("\nExitcode: %u (0x%02x)", exitcode, exitcode);
  }

  printf("\nType <return> to exit: "); fflush(stdout);
  while (!((key = getc(stdin)) == EOF || key == '\n' || key == '\r'))
    ;
  printf("\n");

  return exitcode;
}