run a command that needs input without hanging, but still allow input - c++

I'm making a basic music player in C++ on an embedded Linux platform (Intel Edison).
It works by sending commands to the shell to play the music using mpg123.
Playing the music is working fine, but now I need to add media controls. I'm using the mpg123 command to play my MP3 files and if you pass it the -C flag then it listens for commands such as p for pause, q for quit, etc
I'm using the code from this other SO answer for executing the commands How to execute a command and get output of command within C++ using POSIX?
Now the thing is, when I run the command to play the selected song from c++ (eg. mpg123 -C /media/sdcard/Music/<songname>) it hangs the c++ program until the command returns, which doesn't return until the song is done playing. I can eliminate that issue by using pthead to run the command in a parallel thread, but that still doesn't allow me to enter commands as I need to.
I thought of maybe somehow running the command in another tty, and then somehow passing the commands to mpg123 by sending them to the other tty, but I was unable to find a way to do this. (and I'm not sure it's possable)
I've been trying to do this for hours, so now I'm ready to ask here for some help :)
Do any of you have any ideas on how to run the command without freezing the thread (in a pthread or whatever), and still be able to send commands to mpg123?

It sounds like you'll want to use mpg123's FIFO mode. You set a pathname to be used, point mpg123 at it and then echo your commands into it.
This answer has a great example
FIFO_MPG='/srv/http/newsctl'
mpg123 -R --fifo "$FIFO_MPG"
echo 'load filename.mp3' >> "$FIFO_MPG"

Related

C++ executable, sh 1:not found

I created a c++ programm that works with ros. The first step would be to open a roscore in a terminal and move on from there. I do so with system("roscore &");
I compiled my file and can run it just fine with ./file.
However, I want to be able to run it as an application (double click). I created a .desktop file and the program shows up in my application list. When i start it though, all I get is a terminal that opens with the message
sh: 1: roscore: not found
etc.
The same applies for the roslaunch commands. I also fork and exec a roslaunch command, which does not work as well.
I tried system("ls"); which worked. All cout messages work as well.
Any idea what is wrong here?
roscore executable is not located in std paths (/bin:/usr/bin:). Use the absolute path - system("/path/to/roscore &")

Why isn't gdb working for me

Background
I am currently trying to build an autonomous drone using ROS on my Rapsberry Pi which is running an Ubuntu MATE 16.04 LTS. Solving the Computer Vision problem of recognising red circles as of now.
Specific Problem
I am constantly getting the error I get in this question. To help me solve this, I have decided to use gdb. However, the command rosrun --prefix 'gdb run --args' zlab_drone vdstab does not seem to be working for me. zlab_drone is the name of the package and vdstab is the name of the executable I am trying to run. Since this is inside a ROS environment, I have grabbed the syntax from here, and used the suggestions in this question.
When I invoke this command, even with tui, I get a SIGSEGV and when I invoke list inside gdb itself, the program does not stay at a particular point and keeps listing a different line till it is out of range. This is quite a weird issue.
I managed to make it work without this issue earlier by using a different command, I reckon. I just cannot remember how I made it work last time.
Well, in the link you mentioned, it states clear that you should use either :
launch-prefix="xterm -e gdb --args" : run your node in a gdb in a separate xterm window, manually type run to start it
or :
launch-prefix="gdb -ex run --args" : run your node in gdb in the same xterm as your launch without having to type run to start it
So, it really looks like you missed an -ex as #ks1322 suggeseted in the comments or just type run to start the debug process.
I found out about this exclusive bug that relates to Raspberry Pi's solely. Basically the solution involves, as quoted by Peter Bennet:
There is a workaround. Start the program, then from another command
prompt or from an ssh remote login, use gdp -p xxxxx where xxxxx is
the process number. This works without crashing. If you need to debug
something that happens before you can get in from another command
prompt, add to the program a command that stops process at the
beginning of main, for example a call to gets, which will wait for you
to press enter before continuing.

Start / stop CAN boards from userspace using libsocketcan

I am trying to start / stop CAN boards or to update their baudrate using SocketCAN from userspace. My tests are performed on PeakSystem and IXXAT USB-to-CAN V1/V2 boards.
My first attempt was to use visudo and to enable NOPASSWD to "ip link set ...", and then to call "sudo ip link set ..." in my C++ code.
Complete visudo line is:
%sudo ALL=(ALL:ALL) NOPASSWD: /bin/ip link set can[0123456789]* type can bitrate [0123456789]*, /bin/ip link set can[0123456789]* up, /bin/ip link set can[0123456789]* down
Then, I tried with Linux capabilities by adding capabilities to /bin/ip. That allows me to call "ip link set ..." from my C++ code which was even better.
Add capabilities command:
sudo setcap cap_net_raw,cap_net_admin+ep /bin/ip
But then I discovered libsocketcan which is a far better approach than calling command lines from C++. However when calling "can_set_bitrate" or "can_do_start", I have an error "RTNETLINK: Operation not permitted". But things are working fine when my program is launched as root. Other functions like can_get_state are working fine in userspace (actually, they are returning : 4 -> CAN_STATE_STOPPED).
I tried to adding capabilities to my program without any success ""sudo setcap cap_net_raw,cap_net_admin+ep ./myprogram".
How can I allow my program to use libsocketcan in userspace?
Thanks for your help!
sudo setcap cap_net_raw,cap_net_admin+ep your_executable is the solution. You may need to compile with -Wl,-rpath so your program finds its shared libraries (also see this answer)

How do I open a terminal window with C++ in Ubuntu?

I recently decided to start teaching myself C++ and thought a simple encryption project would be a good place to start, since it covers most of the basics (cout, cin, opening files, etc). Is there a way to have the code open a terminal window similar to the one opened when I compile and run from sublime text?
I have tried this so far, but it hasn't changed anything.
string cmd = "gnome-terminal-x sh-c 'ls-l; exec bash'";
system(cmd.c_str());
Essentially, I would like to be able to run the program by clicking the .exe, and have the terminal where all of the input and output goes pop up.
You don't need to write any code, you just need to configure the shortcut to launch the program in a terminal. Here's a Gnome dialog that shows that option:
Problem seems to be gnome-terminal, or then just my failure to give it the right arguments. For example gnome-terminal -x sh -c 'ls -l ; exec bash' from command line in another terminal just opens an empty gnome-terminal and spits out a bunch of glib warnings to original terminal... (Note to readers: if you can give the right command that works for gnome-terminal, please let me know in comments or just edit this paragraph.)
However, using xterm works, for example xterm -e sh -c 'ls -l; exec bash', or a line for your code:
string cmd = "xterm -e sh -c 'ls -l; exec bash'";
As a side note, the command to open the default x terminal window of the DE is x-terminal-emulator, but it quite often has the practical problem of different terminals taking different arguments, so sadly you're probably better of using a specific terminal, like that xterm, and requiring that to be installed, or letting user to configure what terminal to use, with what arguments (though letting user to specify any command to be run can also be a security risk, if user is not always trusted).
Just be very careful with escaping. For example, when you test the command form command line, and then copy-paste it to C++ string literal, you need to escape every " and \ one more time for C++. If you have trouble with this, check out C++11 raw strings.
Escaping becomes extra important if you construct the command string at runtime, and especially if you accept user input and add that to the string. In that case, better search for and use some existing library like GLib, or sanitize the user input very carefully (ie. just paranoidically reject anything with chars, which may have a special meaning in shell in some context).
If you are actually asking, how can my program open a console window for itself similar to how Windows console programs behave, and redirect it's own stdin, stdout and stderr there, as if it was launched from command line, that that is not very easy from the same binary, and it is not commonly done like that in Unix.
If you want a behaviour like that, you could create a desktop shortcut, but more general way is to write a wrapper shell script, which starts your binary in a terminal. What kind of script exactly, depends on how you want it to behave exactly: what will it do with stdio, will it return or wait for program to exit, how do you want it to find the binary, how does it behave when run from command line instead of double-clicking from GUI, etc.

C++ Keep process alive after it kills its parent

I'm working on implementing a self-updater for a daemon on OS X. The update is published as a .pkg file, so what I'm trying to do is as follows:
When the daemon is notified that an update is available, it calls installer via the system() call to install the package. The package contains a newer version of the daemon, a preupgrade script that stops the daemon (launchctl unload /Library/LaunchDaemons/foo.plist), and a postflight script that starts it back up after the new version is installed. The problem I'm having is that the installer process is quitting prematurely. I suspect that it may be because the installer kills its parent process in order to update it, and then gets killed itself instead of continuing as its own orphan process. I've tried the following with no luck:
Postpending the installer command with '&' to run it in the
background
Wrapping the installer command with nohup
The install command completes consistently without error when I run it from the command line, and fails consistently when run from the installer. When called from the installer, I'm piping the output to a file, and sometimes it has nothing, and sometimes it shows the install getting to about 41% completion before output stops. Any ideas on how I can figure out what's happening to the process or make sure it stays alive without its parent?
When you call launchctl unload, it kills the entire process group (unlike a simple kill). You want to move your subprocess into a separate process group. The easiest way is with the C call setsid().
If you're in the middle of a shell script, you should look at the following approaches. I haven't tried these since I was dealing with a C program and could setsid():
Prior to calling the installer, use set -m. This is supposed to turn on monitor mode, which says "Background processes run in a separate process group and a line containing their exit status is printed upon their completion."
Try this sub-interative shell trick: New process group in shell script