{"id":643,"date":"2012-10-19T11:16:48","date_gmt":"2012-10-19T11:16:48","guid":{"rendered":"https:\/\/raspberry-projects.com\/pi\/?p=643"},"modified":"2020-04-07T11:00:44","modified_gmt":"2020-04-07T11:00:44","slug":"using-console-commands-in-code","status":"publish","type":"post","link":"https:\/\/raspberry-projects.com\/pi\/programming-in-c\/console\/using-console-commands-in-code","title":{"rendered":"Using console commands in code"},"content":{"rendered":"\n<p>The command line in Linux is so incredibly powerful with so many functions available to you via the OS and optional applications you can install. &nbsp;It is often the easiest&nbsp;solution in C++ programs to just use the command line to achieve something&nbsp;you need doing&nbsp;rather&nbsp;than finding a&nbsp;harder way to do it in code and the following examples let you do just&nbsp;that.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;stdlib.h>\n\t\/\/Console command:\n\tsystem(\"cp file.x newfile.x\");\n\n\t\/\/Execute file:\n\texeclp(\"\/usr\/bin\/omxplayer\", \" \", \"\/home\/pi\/projects\/game\/audio\/alpha.wav\", NULL);\t\t\/\/Execute file: file, arguments (1 or more strings followed by NULL - omxplayer has &#91;OPTIONS] &#91;FILE] hence the blank string)<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">System Function (Calling shell)<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;stdlib.h>\n\n\n\tsystem(\"cp file.x newfile.x\");<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Call On A Background Thread<\/h4>\n\n\n\n<p>Can you get away with just adding a &#8216;&amp;&#8217; to the end of the line to cause it to be done in the background? &nbsp;If not:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;unistd.h>\n\tint pid;\n\tpid=fork();\n\tif(pid==0)\n\t{\n\t\t\/\/printf(\"I am the child\\n\");\n\t\texeclp(\"\/usr\/bin\/omxplayer\", \" \", \"\/home\/pi\/projects\/game\/audio\/alpha.wav\", NULL);\t\t\/\/Execute file: file, arguments (1 or more strings followed by NULL - omxplayer has &#91;OPTIONS] &#91;FILE] hence the blank string)\n\t\t_exit(0);\n\t}\n\telse\n\t{\n\t\t\/\/printf(\"I am the parent\\n\");\n\t\twait();\n\t} <\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Running as a different&nbsp;root user<\/h4>\n\n\n\n<p>If your application has been run as root user with sudo because you are using the IO pins you may want to make command lines calls as the standard pi user. &nbsp;You can change to a different user using su &#8211; USERNAME -c before the command and surrounding it with quotes.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\tsystem(\"su - pi -c \\\"fetchmail > \/dev\/null\\\"\");<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Getting The Result Of An Executed Console Command<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;string>\n#include &lt;iostream>\n#include &lt;stdio.h>\nusing namespace std;    \/\/Or use std::string;\n\n\/\/************************************************************\n\/\/************************************************************\n\/\/********** EXECUTE CONSOLE COMMAND AND GET RESULT **********\n\/\/************************************************************\n\/\/************************************************************\n\/\/Note, this will return the output stdout. Some commands may generate a stderr response instead of stdout which you'd see on the console but this won't\n\/\/return, unless you simply add \" 2>&amp;1\" to the end of your command string.  Then you'll get the output of stdout and stderr\nstring do_console_command_get_result (char* command)\n{\n\tFILE* pipe = popen(command, \"r\");\t\t\/\/Send the command, popen exits immediately\n\tif (!pipe)\n\t\treturn \"ERROR\";\n\t\n\tchar buffer&#91;128];\n\tstring result = \"\";\n\twhile(!feof(pipe))\t\t\t\t\t\t\/\/Wait for the output resulting from the command\n\t{\n\t\tif(fgets(buffer, 128, pipe) != NULL)\n\t\t\tresult += buffer;\n\t}\n\tpclose(pipe);\n\treturn(result);\n}<\/code><\/pre>\n\n\n\n<h5 class=\"wp-block-heading\">If you want to run a command \/ tool that will run&nbsp;continuously<\/h5>\n\n\n\n<p>Use <a href=\"https:\/\/raspberry-projects.com\/pi\/programming-in-c\/threads\/running-a-command-line-tool-on-a-child-thread\">this example here<\/a><\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Getting The Result Of An Executed Console Command &#8211; In The Background<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>#include &lt;string>\n#include &lt;iostream>\n#include &lt;stdio.h>\n#include &lt;fcntl.h>\nusing namespace std;    \/\/Or use std::string;\n\n\n\/\/******************************************************************\n\/\/********** EXECUTE CONSOLE COMMAND AND GET RESULT ASYNC **********\n\/\/******************************************************************\n\nstatic FILE* pipe;\nstatic string result;\nchar buffer&#91;128];\n\n\tswitch (my_state_machine)\n\t{\n\t\tcase start_request:\n\t\t\t\/\/----- START THE REQUEST -----\n\n\t\t\t\/\/Note, this will return the output stdout. Some commands may generate a stderr response instead of stdout which you'd see on the console but this won't\n\t\t\t\/\/return, unless you simply add \" 2>&amp;1\" to the end of your command string.  Then you'll get the output of stdout and stderr\n\t\t\tpipe = popen(\"wget -qO- \\\"mydomain.com\/something.php\\\"\", \"r\");\t\t\/\/Send the command, popen exits immediately\n\t\t\tif (!pipe)\n\t\t\t{\n\t\t\t\tcout &lt;&lt; \"ERROR\" &lt;&lt; endl;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\/\/Set flags so fgets becomes non blocking\n\t\t\tint file_descriptor = fileno(pipe);\n\t\t\tint flags = fcntl(file_descriptor, F_GETFL, 0);\n\t\t\tflags |= O_NONBLOCK;\n\t\t\tfcntl(file_descriptor, F_SETFL, flags);\n\n\t\t\tresult = \"\";\n\n\t\t\tmy_state_machine = waiting_for_response;\n\t\t\tbreak;\n\n\n\t\tcase waiting_for_response:\n\t\t\t\/\/----- WAITING FOR RESPONSE -----\n\n\t\t\twhile(fgets(buffer, sizeof(buffer), pipe) != NULL)\n\t\t\t{\n\t\t\t\tresult += buffer;\n\t\t\t}\n\n\t\t\tif (feof(pipe))\n\t\t\t{\n\t\t\t\tcout &lt;&lt; \"Complete: \" &lt;&lt; result &lt;&lt; endl;\n\t\t\t\tpclose(pipe);\n\t\t\t\tmy_state_machine = idle;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\t\t\n\t}<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>The command line in Linux is so incredibly powerful with so many functions available to you via the OS and optional applications you can install. &nbsp;It is often the easiest&nbsp;solution in C++ programs to just use the command line to achieve something&nbsp;you need doing&nbsp;rather&nbsp;than finding a&nbsp;harder way to do it in code and the following [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[28],"tags":[],"class_list":["post-643","post","type-post","status-publish","format-standard","hentry","category-console"],"_links":{"self":[{"href":"https:\/\/raspberry-projects.com\/pi\/wp-json\/wp\/v2\/posts\/643","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/raspberry-projects.com\/pi\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/raspberry-projects.com\/pi\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/raspberry-projects.com\/pi\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/raspberry-projects.com\/pi\/wp-json\/wp\/v2\/comments?post=643"}],"version-history":[{"count":22,"href":"https:\/\/raspberry-projects.com\/pi\/wp-json\/wp\/v2\/posts\/643\/revisions"}],"predecessor-version":[{"id":3216,"href":"https:\/\/raspberry-projects.com\/pi\/wp-json\/wp\/v2\/posts\/643\/revisions\/3216"}],"wp:attachment":[{"href":"https:\/\/raspberry-projects.com\/pi\/wp-json\/wp\/v2\/media?parent=643"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/raspberry-projects.com\/pi\/wp-json\/wp\/v2\/categories?post=643"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/raspberry-projects.com\/pi\/wp-json\/wp\/v2\/tags?post=643"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}