comparison Core/Toolbox.cpp @ 1050:64f1842aae2e

Toolbox::ExecuteSystemCommand
author Sebastien Jodogne <s.jodogne@gmail.com>
date Wed, 23 Jul 2014 11:36:35 +0200
parents 0bfeeb6d340f
children e07b90fb00eb
comparison
equal deleted inserted replaced
1049:bd2cb95003da 1050:64f1842aae2e
42 #include <boost/date_time/posix_time/posix_time.hpp> 42 #include <boost/date_time/posix_time/posix_time.hpp>
43 #include <boost/uuid/sha1.hpp> 43 #include <boost/uuid/sha1.hpp>
44 #include <algorithm> 44 #include <algorithm>
45 #include <ctype.h> 45 #include <ctype.h>
46 #include <boost/regex.hpp> 46 #include <boost/regex.hpp>
47 #include <glog/logging.h>
47 48
48 #if defined(_WIN32) 49 #if defined(_WIN32)
49 #include <windows.h> 50 #include <windows.h>
51 #include <process.h> // For "_spawnvp()"
52 #else
53 #include <unistd.h> // For "execvp()"
54 #include <sys/wait.h> // For "waitpid()"
50 #endif 55 #endif
51 56
52 #if defined(__APPLE__) && defined(__MACH__) 57 #if defined(__APPLE__) && defined(__MACH__)
53 #include <mach-o/dyld.h> /* _NSGetExecutablePath */ 58 #include <mach-o/dyld.h> /* _NSGetExecutablePath */
54 #include <limits.h> /* PATH_MAX */ 59 #include <limits.h> /* PATH_MAX */
949 doc.save(writer, " ", pugi::format_default, pugi::encoding_utf8); 954 doc.save(writer, " ", pugi::format_default, pugi::encoding_utf8);
950 writer.Flatten(target); 955 writer.Flatten(target);
951 } 956 }
952 957
953 #endif 958 #endif
959
960
961 void Toolbox::ExecuteSystemCommand(const std::string& command,
962 const std::vector<std::string>& arguments)
963 {
964 // Convert the arguments as a C array
965 std::vector<char*> args(arguments.size() + 2);
966
967 args.front() = const_cast<char*>(command.c_str());
968
969 for (size_t i = 0; i < arguments.size(); i++)
970 {
971 args[i + 1] = const_cast<char*>(arguments[i].c_str());
972 }
973
974 args.back() = NULL;
975
976 int status;
977
978 #if defined(_WIN32)
979 // http://msdn.microsoft.com/en-us/library/275khfab.aspx
980 status = static_cast<int>(_spawnvp(_P_OVERLAY, command.c_str(), &args[0]));
981
982 #else
983 int pid = fork();
984
985 if (pid == -1)
986 {
987 // Error in fork()
988 LOG(ERROR) << "Cannot fork a child process";
989 throw OrthancException(ErrorCode_SystemCommand);
990 }
991 else if (pid == 0)
992 {
993 // Execute the system command in the child process
994 execvp(command.c_str(), &args[0]);
995
996 // We should never get here
997 _exit(1);
998 }
999 else
1000 {
1001 // Wait for the system command to exit
1002 waitpid(pid, &status, 0);
1003 }
1004 #endif
1005
1006 if (status != 0)
1007 {
1008 LOG(ERROR) << "System command failed with status code " << status;
1009 throw OrthancException(ErrorCode_SystemCommand);
1010 }
1011 }
954 } 1012 }
955 1013