Executing unix commands in C++ - c++

Is there a way to use the unix 'time' command in C++ and store each of its outputs in a variable?
EDIT: If there isn't a way, then what about calling time in a bash script and storing the returned values some way?
Thank you!

Supposing you are on UNIX, then the C++ standard std::system function will behave as defined in POSIX, that is, execute a command as with sh. Before doing this, you can connect your own stdin and stdout to a local pipe by first using dup to create aliases of STDIN_FILENO and STDOUT_FILENO, then close the aforementioned file descriptors, then pipe to open a pipe on the newly freed descriptors.
Then you can interact with std::cin and std::cout. Well, it would be a good idea to flush the C++ interface before beginning.
This isn't all really a good idea, though. It should be simpler to use the POSIX C interface to get the relevant data directly.

If you are ok with using Boost libraries, then this should do it http://www.boost.org/doc/libs/1_49_0/doc/html/date_time/examples.html#date_time.examples.seconds_since_epoch
the good part is it also handles time zones conversions :)

You can use system(3) or popen(3), but there's almost always a better, more portable, and native solution, depending on what exactly you're looking for. In your specific case it seems like what you're really looking for a combination of getrusage(2) and ftime(3).

Related

How to control stdin echo in C++?

In Linux, I can use tcsetattr, but I want to write a portable C++ program that can turn echo of cin on and off (for entering a password). Is there something in std::io* that supports this?
Unfortunately there is no portable way to disable console echo, so you have to use OS specific API. You can use preprocessor to write portable program, but you would have to write separate code for supported OS and wrap it into #ifdef condition. Another solution would be to use portable library if such one exists, that would do this under the hood for you.
No, there is not. C/C++'s IO libraries are based around the "stream" model, where input comes from some random source of characters (generally the console) and output is similarly sent to some random character target. In a sense, it isn't C/C++ doing the echoing at all -- it's the console system -- so there's no way for it to control whether the echoing occurs.

Sending arguments to executables from another program

I know this can easily be done using the platform's system() implementation. However, from what I have read using system is often not the best approach and can lead to security drawbacks. Is there a different industry standard approach to this type of problem? What are the options available to the user to do this sort of thing?
I am specifically interested in the implementation in C/C++, but I do not think this type of thing will be language dependent; I suspect it shall be platform specific.
You might be looking for the standard POSIX functions fork and exec*. This works for Unix-like platforms (Linux and Mac).
On Windows, there's the CreateProcess API.
fork and exec are a little odd, because fork duplicates your current process entirely and returns different results to each copy. The new copy of the program should then set up any needed settings (closing files that shouldn't be open in both programs, changing environment variables, etc.) and finally call one of the exec functions, which replaces that process with the specified program (while maintaining the currently open file descriptors and such).
The security issue which you alluded to with system is that system uses the system's shell to execute the program and parse its arguments, and if you're not careful, the shell can do things you don't want. (For example, "ls " + argument seems innocuous, but it can delete data if argument is "; rm -rf /*").
If you control the arguments, or if you're careful to escape any shell metacharacters in your parameters to system, you should be okay, although it's most reliable to avoid it.
To avoid the security issue, use a method of spawning a program that lets you specify a list of arguments, already parsed, instead of specifying a string that has to be parsed to extract arguments:
Using POSIX, fork then call one of the exec functions.
On Windows, use CreateProcess.
Use a cross-platform library function like the Apache Portable Runtime's apr_proc_create.
These don't exactly match system()'s behavior (system, for example, does a bit with signal handling and return values), but they're close.
You've likely already seen it's mention, but fork() and exec are typically the choices to go with in Linux programming, but for Windows, you'd have to use the OS API to create a new process. system() is still a good choice for smaller project because they typically don't run into the same malicious problems that big-name software can. It also natively waits for the child application to return before continuing on in the parent program, which can be a nice trait if you're using an external binary to run calculations or something else and you'll be getting the return value.
A lot of people will tell you that using system() is wrong, but it's really not. It's frowned upon in the professional market because of its inherent problems, but otherwise it works.

Can C be used to capture system calls on a machine?

Good day,
I was wondering if there is a way to do direct system call capture with C or C++?
I know that currently on unix systems you can use SystemTap to do system capture. The problem I'm having is that in order to feed them into another program for analysis I have to pipe them to the other program.
I'd like to pass things along programatically as this is easier than "printing" out into the pipe and then reading in with the other program.
Is there a way of doing this? How difficult would it be?
strace does exactly that.
You can take a look at its source code to see how its done.

how to make sure that a file will be closed at the end of the run

Suppose someone wrote a method that opens a certain file and forgets to close it in some cases. Given this method, can I make sure that the file is closed without changing the code of the original method?
The only option I see is to write a method that wraps the original method, but this is only possible if the file is defined outside the original method, right? Otherwise it's lost forever...
Since this is C++, I would expect that the I/O streams library (std::ifstream and friends) would be used, not the legacy C I/O library. In that case, yes, the file will be closed because the stream is closed by the stream object's destructor.
If you are using the legacy C API, then no, you're out of luck.
In my opinion, the best answer to an interview question like this is to point out the real flaw in the code--managing resources manually--and to suggest the correct solution: use automatic resource management ("Resource Acquisition is Initialization" or "Scope-Bound Resource Management").
You are correct that if the wrapper doesn't somehow get a reference to the opened file, it may be difficult to close it. However, the operating system might provide a means to get a list of open files, and you could then find the one you need to close.
However, note that most (practically all) operating systems take care of closing files when the application exits, so you don't need to worry about a file being left open indefinitely after the program stops. (This may or may not be a reasonable answer to the question you were given, which seems incredibly vague and ambiguous.)
If you are using C function for file open, you can use _fcloseall function for closing all the opened files.
If you are using C++, Like James suggested, stream destructor should take care of it.
Which environment are you in? You can always check the file descriptors opened by the process and close them forcefully.
Under linux you can use the lsof command to list open files for a process. Do it once before the method and once after the method to detect newly opened files. Hopefully you aren't fighting some multithreaded legacy beast.

Pipes to C++ Streams

is it possible to turn pipes genereated via pipe() on a POSIX-system into std::istreams and std::ostreams?
if yes, how?
i would prefer to use << and >> instead of read() and write()
thanks in advance
There are non-standard constructors which take file descriptor number or FILE*. See http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-api-4.5/a00074.html#a777faeb6849444b4663d1cbe543e1ae3
Check out http://www.netbsd.org/~jmmv/process/ and http://www.highscore.de/boost/process/
EDIT http://svn.boost.org/svn/boost/sandbox/process/
I forget which one hosts the latest source, but it's a very good cross-platform IPC library with support for pipes.
It's not actually part of boost but they want (or wanted) it to be.