What I want to do :
1.Create and open for writing in.fifo by process1
2.Open in.fifo for reading in process2
3.Write from cin to in.fifo by process1 line
4.Read and cout line by process2
5.When input "exit" to cin (process2), it closed file in.fifo, delete it and exit
6.process2 exit, because in.fifo has no writer
In my programs process2 doesn't exit. In c it works with read,write when O_NONBLOCK is clear , but I want to do it in c++
write.cpp:
#include <stdlib.h>
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int main(){
std::ofstream fifo;
fifo.open("/home/fedor/projects/fifo2/in",ios::out);
if(! fifo.is_open() ){
std::cout << " error : cannot open file " << std :: endl;
return 1;
}
std::cout << " file open " << std :: endl;
std::string line;
while (line.compare("exit") != 0 ){
std::getline(cin, line);
fifo << line << endl;
/* do stuff with line */
}
fifo.close();
remove("/home/fedor/projects/fifo2/in");
return 0;
}
read.cpp:
#include <stdlib.h>
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int main(){
std::ifstream fifo;
fifo.open("/home/fedor/projects/fifo2/in",ifstream::in);
if(! fifo.is_open() ){
std::cout << " error : cannot open file " << std :: endl;
return 1;
}
std::cout << " file open " << std :: endl;
std::string line;
bool done = false;
while (!done)
{
while (std::getline(fifo, line))
{
cout << line << endl;
/* do stuff with line */
}
if (fifo.eof())
{
fifo.clear(); // Clear the EOF bit to enable further reading
}
else
{
done = true;
}
}
return 0;
}
I can't find where I can read about blocking read by streams like http://linux.die.net/man/3/read about blocking read
If process2 closed if input "exit", like process1 is that a life lock ? (Is it blocking on read, or just trying and trying to read )
There is no way to do what you want using C++ standard library, because in C++ there is no notion of processes and file sharing. You have to use OS-specific APIs, which most likely are C (like open()) but in theory they can be C++.
Your reader appears to explicitly ignore an eof, instead clearing the end of file condition, and continuing. You're saying that your reader isn't exiting. Of course it's not, you're explicitly clearing EOF and continuing. It's going to exit only on an error reading from the FIFO, which is going to be a fairly unusual event.
If you want to exit on an EOF, you'll have to explicitly do that. Or, if you want to terminate on receiving the exit message, your writer isn't going to send it. When the writer itself receives a typed "exit", it terminates without writing it to the fifo (and your reader needs to check for that).
Related
Is it possible to set timeout for std::cin?
For example, std::cin doesn't receive any data during 10 seconds - it throws an exception or returns an error.
Edited:
And what about timer from Boost library? As far as I know, it is portable library. Is it possible to ask timer of Boost library to throw exceptions after predefined period of time? I guess it can solve this problem.
It isn't possible to set a time out for std::cin in a portable way. Even when resorting to non-portable techniques, it isn't entirely trivial to do so: you will need to replace std::cin's stream buffer.
On a UNIX system I would replace the default stream buffer used by std::cin by a custom one which uses file descriptor 0 to read the input. To actually read the input I would use poll() to detect presence of input and set a timeout on this function. Depending on the result of poll() I would either read the available input or fail. To possibly cope with typed characters which aren't forwarded to the file descriptor, yet, it may be reasonable to also turn off the buffering done until a newline is entered.
When using multiple threads you can create a portable filtering stream buffer which uses on thread to read the actual data and another thread to use a timed condition variable waiting either for the first thread to signal that it received data or for the time out to expire. Note that you need to guard against spurious wake-ups to make sure that the timeout is indeed reached when there is no input. This would avoid having to tinker with the actual way data is read from std::cin although it still replaces the stream buffer used by std::cin to make the functionality accessible via this name.
I just figured out how to do that, polling the std::cin file descriptor.
poll function returns 0 if timeout occurs and no event happened, 1 if something happened, and -1 if error happened.
#include <iostream>
#include <signal.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <poll.h>
bool stop = false;
void intHandler(int dummy)
{
stop = true;
}
std::string readStdIn()
{
struct pollfd pfd = { STDIN_FILENO, POLLIN, 0 };
std::string line;
int ret = 0;
while(ret == 0)
{
ret = poll(&pfd, 1, 1000); // timeout of 1000ms
if(ret == 1) // there is something to read
{
std::getline(std::cin, line);
}
else if(ret == -1)
{
std::cout << "Error: " << strerror(errno) << std::endl;
}
}
return line;
}
int main(int argc, char * argv[])
{
signal(SIGINT, intHandler);
signal(SIGKILL, intHandler);
while(!stop)
{
std::string line = readStdIn();
std::cout << "Read: " << line << std::endl;
}
std::cout << "gracefully shutdown" << std::endl;
}
There was a good answer posted here but the author removed it. It's a solution that worked well for me in the application I was developing. This is the essence of what the person wrote:
// compile: g++ -pthread thisfile.cpp
#include <iostream>
#include <thread>
int main() {
int x;
bool inputReceived = false;
time_t startTime = time(NULL);
time_t waitTime = 10;
std::cout << "Enter a number within " << waitTime << " seconds\n";
// spawn a concurrent thread that waits for input from std::cin
std::thread t1([&]() {
std::cin >> x;
inputReceived = true;
});
t1.detach();
// check the inputReceived flag once every 50ms for 10 seconds
while (time(NULL) < startTime + waitTime && !inputReceived) {
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
if (inputReceived) {
std::cout << "x = " << x << "\n";
return EXIT_SUCCESS;
}
std::cout << "timeout\n";
// TODO: find a way to kill the thread
return EXIT_FAILURE;
}
Be aware that the thread continues running after the timeout occurs, but it will terminate when the whole program terminates. If this is all you need then you don't need to worry about it.
However, there is no simple way to kill a detached thread. A solution would be to close the input stream, but that's not easy or desirable to do with std::cin. If you're lucky then you're going to use this with an easily closeable stream instead of std::cin. Closing the stream will cause input statement to fail and the the thread will probably just exit with an internal exception, but at least the thread will terminate.
#include <cstddef>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
//read the lines from the piped file using cin
string response;
int i = 0;
while (getline(cin, response)) {
//if the response is empty, stop
if (response.empty()) {
break;
}
//Write each odd line (1,3, etc..) to stderr (cerr)
//Write each even line (2,4. etc..) to stdout (cout)
if (i % 2 != 1) { //send odd to stderr
cerr << "err: " << response << endl;
}
else { //send even to stdout
cout << "out: " << response << endl;
}
i++;
}
return 0;
}
I want to redirect stderr to /dev/null, how would I go about doing so? I'm new to C++ and trying to learn by practicing, however, I'm not easily able to find an answer that fits my existing program.
Besides the excellent commentary above, it is pretty easy to make a “null” streambuf sink in C++.
#include <iostream>
struct null_streambuf: public std::streambuf
{
using int_type = std::streambuf::int_type;
using traits = std::streambuf::traits_type;
virtual int_type overflow( int_type value ) override
{
return value;
}
};
To use it, just set the rdbuf:
int main()
{
std::cerr.rdbuf( new null_streambuf );
std::cerr << "Does not print!\n";
}
If you wish to be able to turn it off and on, you will have to remember the original and restore it, not forgetting to delete the new null_streambuf.
int main()
{
std::cerr << "Prints!\n";
auto original_cerr_streambuf = std::cerr.rdbuf( new null_streambuf );
std::cerr << "Does not print.\n";
delete std::cerr.rdbuf( original_cerr_streambuf );
std::cerr << "Prints again!\n";
}
This does have the objective effect of being compiled to code, which I suspect is the advantage you are looking for: the ability to dynamically enable and disable diagnostic output.
This is, however, the usual function of a debug build, where you use the DEBUG macro to decide whether or not to compile something (such as error output operations) into the final executable.
Keep in mind that this does not disable output on standard error via other means, but only through cerr.
I've been trying to write a code to read from a file line by line:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream jin("Story.txt");
// ins.open("Story.txt", ios::in);
if (!jin)
{
cout << "File not opened" << endl;
return 1;
}
else{
char a[100];
do
{
jin.getline(a, 100);
cout << a << endl;
}
while (!jin.eof());
jin.close();
return 0;
}
}
However, on executing this program on Visual Studio Code on Windows, it behaves as infinite loop.
Can someone tell what's wrong?
(I am sure that the file Story.txt exists, no doubt about that)
When std::istream::getline has read 100-1 characters (without finding a newline,\n), it will set the failbit on the stream. This prevents further reading on the stream (unless you reset that state). It does however not set eofbit so you are now in a bit of a pickle. The failbit prevents further reading, and eof() returns false, because eofbit is not set - it will therefore loop indefinitely.
If at least one of the lines in Story.txt is longer than 99 chars, the above is what will happen.
The easiest way out is to use a std::string and std::getline instead:
#include <cerrno>
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::ifstream jin("Story.txt");
if(!jin) {
std::cerr << "File not opened: " << std::strerror(errno) << std::endl;
return 1;
}
std::string a;
while(std::getline(jin, a)) {
std::cout << a << '\n';
}
return 0;
}
If you really do not want to use std::getline and std::string, you can, but it's much harder:
#include <cerrno>
#include <cstring>
#include <fstream>
#include <iostream>
int main() {
std::ifstream jin("Story.txt");
if(!jin) {
std::cerr << "File not opened: " << std::strerror(errno) << std::endl;
return 1;
}
char a[100];
while(true) {
jin.getline(a, 100);
std::cout << a; // output what we got
if(jin) {
// got a complete line, add a newline to the output
std::cout << '\n';
} else {
// did not get a newline
if(jin.eof()) break; // oh, the end of the file, break out
// reset the failbit to continue reading the long line
jin.clear();
}
}
}
jin.eof() will only return true if a eof-token is found, and this will not happend unless the file is open. That is what causing your infinite loop.
Then you would probably want something like this:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream jin{"Story.txt"};
if (!jin)
{
cout << "File not opened" << endl;
return 1;
}
for (std::string a; std::getline(jin, a);) { // Read every line
cout << a << "\n";
}
// jin is closed when going out of scope so no need for close();
return 0;
}
I'm looking for a (multiplatform) way to do non-blocking console input for my C++ program, so I can handle user commands while the program continually runs. The program will also be outputting information at the same time.
What's the best/easiest way to do this? I have no problem using external libraries like boost, as long as they use a permissive license.
Example using C++11:
#include <iostream>
#include <future>
#include <thread>
#include <chrono>
static std::string getAnswer()
{
std::string answer;
std::cin >> answer;
return answer;
}
int main()
{
std::chrono::seconds timeout(5);
std::cout << "Do you even lift?" << std::endl << std::flush;
std::string answer = "maybe"; //default to maybe
std::future<std::string> future = std::async(getAnswer);
if (future.wait_for(timeout) == std::future_status::ready)
answer = future.get();
std::cout << "the answer was: " << answer << std::endl;
exit(0);
}
online compiler: https://rextester.com/GLAZ31262
I would do this by creating separate a thread which calls normal blocking IO functions and pass it a callback function which it would call when it got input. Are you sure you need to do what you said you want to do?
As for outputting information at the same time, what would happen if the user was in the middle of typing some input and you printed something?
I've done this on QNX4.5 that doesn't support threads or Boost by using select. You basically pass select STDIN as the file descriptor to use and select will return when a new line is entered. I've added a simplified example loop below. It's platform independent, at least for Unix like systems. Not sure about Windows though.
while (!g_quit)
{
//we want to receive data from stdin so add these file
//descriptors to the file descriptor set. These also have to be reset
//within the loop since select modifies the sets.
FD_ZERO(&read_fds);
FD_SET(STDIN_FILENO, &read_fds);
result = select(sfd + 1, &read_fds, NULL, NULL, NULL);
if (result == -1 && errno != EINTR)
{
cerr << "Error in select: " << strerror(errno) << "\n";
break;
}
else if (result == -1 && errno == EINTR)
{
//we've received and interrupt - handle this
....
}
else
{
if (FD_ISSET(STDIN_FILENO, &read_fds))
{
process_cmd(sfd);
}
}
}
There is one easy way:
char buffer[512];
int point = 0;
...
while (_kbhit()) {
char cur = _getch();
if (point > 511) point = 511;
std::cout << cur;
if (cur != 13) buffer[point++] = cur;
else{
buffer[point] = '\0';
point = 0;
//Run(buffer);
}
}
No block, all in 1 thread. As for me, this works.
Non-blocking console input C++ ?
Ans: do console IO on a background thread and provide a means of communicating between threads.
Here's a complete (but simplistic) test program that implements async io by deferring the io to a background thread.
the program will wait for you to enter strings (terminate with newline) on the console and then perform a 10-second operation with that string.
you can enter another string while the operation is in progress.
enter 'quit' to get the program to stop on the next cycle.
#include <iostream>
#include <memory>
#include <string>
#include <future>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <deque>
int main()
{
std::mutex m;
std::condition_variable cv;
std::string new_string;
bool error = false;
auto io_thread = std::thread([&]{
std::string s;
while(!error && std::getline(std::cin, s, '\n'))
{
auto lock = std::unique_lock<std::mutex>(m);
new_string = std::move(s);
if (new_string == "quit") {
error = true;
}
lock.unlock();
cv.notify_all();
}
auto lock = std::unique_lock<std::mutex>(m);
error = true;
lock.unlock();
cv.notify_all();
});
auto current_string = std::string();
for ( ;; )
{
auto lock = std::unique_lock<std::mutex>(m);
cv.wait(lock, [&] { return error || (current_string != new_string); });
if (error)
{
break;
}
current_string = new_string;
lock.unlock();
// now use the string that arrived from our non-blocking stream
std::cout << "new string: " << current_string;
std::cout.flush();
for (int i = 0 ; i < 10 ; ++i) {
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << " " << i;
std::cout.flush();
}
std::cout << ". done. next?\n";
std::cout.flush();
}
io_thread.join();
return 0;
}
sample test run:
$ ./async.cpp
first
new string: first 0 1las 2t 3
4 5 6 7 8 9. done. next?
new string: last 0 1 2 3 4 5 6 7 8quit 9. done. next?
ncurses can be a good candidate.
The StdinDataIO class of the BSD-licensed MUSCLE networking library supports non-blocking reads from stdin under Windows, MacOS/X, and Linux/Unix ... you could use that (or just examine the code as an example of how it can be done) if you want.
You can use the tinycon library to do this. Just spawn a tinycon object in a new thread, and you are pretty much done. You can define the trigger method to fire off whatever you'd like when enter is pressed.
You can find it here:
https://sourceforge.net/projects/tinycon/
Also, the license is BSD, so it will be the most permissive for your needs.
libuv is a cross-platform C library for asynchronous I/O. It uses an event loop to do things like read from standard input without blocking the thread. libuv is what powers Node.JS and others.
In a sense, this answer is incomplete. But yet, I think it can be useful even for people who have different platforms or circumstances, giving the idea, what to look for in their platform.
As I just wrote some scripting engine integration into an SDL2 main event loop (which is supposed to read lines from stdin if there are lines to be read), here is how I did it (on linux (debian bullseye 64 bit)). See below.
But even if you are not on linux, but on some other posix system, you can use the equivalent platform APIs of your platform. For example, you can use kqueue on FreeBSD. Or you can consider using libevent for a bit more portable approach (still will not really work on Windows).
This approach might also work on Windows if you do some special fiddling with the rather new-ish ConPTY. In traditional windows console applications, the problem is, that stdin is not a real file handle and as such, passing it to libevent or using IOCP (IO completion ports) on it will not work as expected.
But, this approach should also work on posix systems, if there is redirection at play. As long as there is a file handle available.
So how does it work?
Use epoll_wait() to detect if there is data available on stdin. While consoles can be configured in all sorts of ways, typically, they operate on a line by line basis (should also apply for ssh etc.).
Use your favorite getline() function to read the line from stdin. Which will work, because you know, there is data and it will not block (unless your console is not defaulting to line by line handling).
Rince and repeat.
#include <unistd.h>
#include <sys/epoll.h>
#include <iostream>
#include <string>
#include <array>
using EpollEvent_t = struct epoll_event;
int main(int argc, const char* argv[]) {
//
// create epoll instance
//
int epollfd = epoll_create1(0);
if (epollfd < 0) {
std::cout << "epoll_create1(0) failed!" << std::endl;
return -1;
}
//
// associate stdin with epoll
//
EpollEvent_t ev;
ev.data.ptr = nullptr;
ev.data.fd = STDIN_FILENO; // from unistd.h
ev.data.u32 = UINT32_C(0);
ev.data.u64 = UINT64_C(0);
ev.events = EPOLLIN;
if (epoll_ctl(epollfd, EPOLL_CTL_ADD, STDIN_FILENO, &ev) < 0) {
std::cout
<< "epoll_ctl(epollfd, EPOLL_CTL_ADD, fdin, &ev) failed."
<< std::endl;
return -1;
}
//
// do non-blocking line processing in your free running
// main loop
//
std::array<EpollEvent_t,1> events;
bool running = true;
while (running) {
int waitret = epoll_wait(epollfd,
events.data(),
events.size(),
0); // 0 is the "timeout" we want
if (waitret < 0) {
std::cout << "epoll_wait() failed." << std::endl;
running = false;
}
if (0 < waitret) { // there is data on stdin!
std::string line;
std::getline(std::cin, line);
std::cout
<< "line read: [" << line << "]" << std::endl;
if (line == "quit")
running = false;
}
// ... Do what you usually do in your main loop ...
}
//
// cleanup of epoll etc.
//
close(epollfd);
return 0;
}
You could do:
#include <thread>
#include <chrono>
#include <string>
#include <iostream>
int main() {
std::cout << "Type exit to quit." << std::endl;
// initialize other std::thread handlers here
std::string input;
while (input != "exit") {
std::getline(std::cin, input);
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
std::cout << "Cleaning up and quitting" << std::endl;
return 0;
};
A simple answer with thread/future and reading a single char at a time (you can replace getchar with cin as required)
Timeout is set to zero and a new future is created every time the previous call is completed.
Like cin, getchar requires that the user hits the RETURN key to end the function call.
#include <chrono>
#include <cstdio>
#include <future>
#include <iostream>
#include <thread>
static char get_usr_in()
{
return std::getchar();
}
int main()
{
std::chrono::seconds timeout(0);
std::future<char> future = std::async(std::launch::async, get_usr_in);
char ch = '!';
while(ch!='q') {
if(future.wait_for(timeout) == std::future_status::ready) {
ch = future.get();
if(ch!='q') {
future = std::async(std::launch::async, get_usr_in);
}
if(ch >= '!' && ch <'~')
std::cout << "ch:" << ch << std::endl;
}
std::cout << "." << std::endl;
}
exit(0);
}
Why not use promises?
#include <iostream>
#include <istream>
#include <thread>
#include <future>
#include <chrono>
void UIThread(std::chrono::duration<int> timeout) {
std::promise<bool> p;
std::thread uiWorker([&p]() {
bool running = true;
while(running) {
std::string input;
std::cin >> input;
if(input == "quit") {
p.set_value(true);
running = false;
}
}
});
auto future = p.get_future();
if (future.wait_for(timeout) != std::future_status::ready) {
std::cout << "UI thread timed out" << std::endl;
uiWorker.detach();
return;
}
uiWorker.join();
}
int main()
{
std::thread uiThread(UIThread, std::chrono::seconds(3));
std::cout << "Waiting for UI thread to complete" << std::endl;
uiThread.join();
}
online complier
I have create a simple application which using C++ and produce a executable file.
I would like to ensure the process cannot be start twice. How to enforce a process/service is start once only ?
Thanks.
What operating system? On Windows, the typical way to do this is to create a named Mutex, because the OS will give you an ERROR_ALREADY_EXISTS if some other process already created a mutex with that name, and the OS will ensure that the mutex is released when the process ends (even if it crashes or is killed).
Write a temporary file and use it as a lock.
Edit: To answer the comment: If you are on a Unix system, write a file /tmp/my_application_lock_file. If it already exists, stop your program with an appropriate message. On exit of the creator of the file, delete it.
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#include <iostream>
#include <fstream>
int main (void)
{
struct stat file_info;
// test for lock file
if (stat("/tmp/my_application_lock", &file_info) == 0) {
std::cout << "My application is already running, will abort now..." << std::endl;
return -1;
} else {
// create lock file
std::ofstream out;
out.open("/tmp/my_application_lock");
if (!out) {
std::cout << "Could not create lock file!" << std::endl;
return -1;
}
out << "locked" << std::endl;
out.close();
// do some work
std::string s;
std::cin >> s;
// remove lock file
errno = 0;
if (unlink("/tmp/my_application_lock"))
std::cout << "Error: " << strerror(errno) << std::endl;
}
return 0;
}