I am trying to write a program in c++ for QNX which executes other programs.
For this I have 4 files to be handled.
file1
file2.l
file3.c
file4.bin
The algorithm is
if file1 is not present then execute file2.l
Execute file3.c
Execute file4.bin
This is the code which I have tried.
#include<fstream>
#include<iostrea>
using namespace std;
int main(){
ifstream ifile;
ifile.open("file1");
if(!ifile){
// system("Code to run file2.l program in termnal")
}
// system("Code to run file3.c program in termnal")
system("./file4.bin")
I need to know how to execute file2.l and file3.c using c++ in QNX
System() is only for executing system functions, such as 'cp' or 'shutdown'.
To launch a program, you can use spawn() or spawnv() functions.
#include <iostream>
using namespace std;
inline bool fileCheck(const string &name)
{
if (FILE *file = fopen(name.c_str(), "r"))
{
fclose(file);
return true;
}
else
{
return false;
}
}
int main(void)
{
// Replace with your own code
if (fileCheck("time.exe"))
{
// exists...
system("swap.exe");
}
else
{
// doesn't exists...
system("swap.exe");
}
return 0;
}
The program firstly creates an inline function to check the existence of a file in a fast way and then the main() occurs which does your required works.
Related
I have a c++ code where, I'm redirecting the stdout to a string. The code should be platform independent. In windows works fine, but under linux it doesn't builds.
Here is my code:
#include <fcntl.h>
int outBuffer[2];
int orgStdOutBuffer;
std::string stringBuff;
enum PIPES {READ, WRITE};
orgStdOutBuffer = dup(fileno(stdout));
outBuffer[READ] = 0;
outBuffer[WRITE] = 0;
if (_pipe(mStdOutBuffer, 65535, O_BINARY) == -1) {
return false;
}
fflush(stdout);
dup2(outBuffer[WRITE], fileno(stdout));
The problem is where I'm checking the end of the pipe:
if (!eof(outBuffer[READ])) {
stdOutBufferSize = read(outBuffer[READ], &(*stringBuff.begin()), buffSize);
}
Under linux gives the following error:
'eof' was not declared in this scope
'O_BINARY' was not declared in this scope
Can anybody help how can I make this code run under linux?
All, the first part of my homework assignment is simply a demo program that I need to compile, and then modify. It was provided by the teacher, however I simply cannot get it to compile using g++. I will be creating a make file at the end of the assignment, but for the moment I am simply trying to test it out, and am having no luck. I've tried the most basic g++ command: g++ -o main TwoPipesTwoChildren.cpp . Can someone please help? I can't even get started on this until I can get this working.
// description: This program will execute "ls -ltr | grep 3376"
// by using a parent and child process
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char **argv){
printf("TEST");
int status;
int childpid;
char *cat_args[] = {"ls", "-ltr", NULL};
char *grep_args[] = {"grep", "3376", NULL};
// create one pipe to send the output of "ls" process to "grep" process
int pipes[2];
pipe(pipes);
// fork the first child (to execute cat)
if((childpid = fork()) == -1)
{
perror("Error creating a child process");
exit(1);
}
// replace cat's stdout with write part of 1st pipe
if (childpid == 0)
{
dup2(pipes[1], 1);
printf("AFTER FORK CHILD");
//close all pipes (very important!); end we're using was safely copied
close(pipes[0]);
close(pipes[1]);
execvp(*cat_args, cat_args);
exit(0);
}
else
{
// replace grep's stdin with read end of 1st pipe
dup2(pipes[0], 0);
close(pipes[0]);
close(pipes[1]);
execvp(*grep_args, grep_args);
}
return (0);
}
I am trying to print the path of the current directory using
this
execl ("/bin/pwd", "pwd", NULL);
output: /home/user/Ubuntu
and want to print a desired text before the current path.
for example:
my name /home/user/ubntu
how this will be done?
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <unistd.h>
#include <dirent.h>
using namespace std;
int main(){
string command;
while(command != "exit"){
cout<< "B-17235"<<return execl ("/bin/pwd", "pwd", NULL);
cin>> command;
}
return 0;
}
Think that the majority of Unix-Linux-Gnu commands are written in C or C++. Generally there are direct API calls either system calls (man 2) or standard C library (man 3) to get the information or do the job.
To get working directory, just use getcwd() as suggested by alk.
char buffer[256];
if (NULL == getcwd(buffer, sizeof(buffer))) {
perror("can't get current dir");
return 1;
}
If you wanted to get the output of a more complex command, the most direct way would be to use popen that encloses the fork, exec, and pipe management for you :
FILE *fd = popen("/bin/pwd", "r");
char buffer[256];
if (fgets(buffer, sizeof(buffer), fd) == NULL) {
perror("can't read command");
return 1;
}
if (buffer[strlen(buffer) - 1] != '\n') {
fprintf(stderr, "path too long";
return 1;
}
pclose(fd);
// ok the working directory is is buffer
You should not use that for a command as simple as pwd.
And don't forget : man is your friend ! man getcwd and man popen will give you plenty of information ...
I am trying to print the path of the current directory
Use the library function getcwd().
To have the function available it might be necessary to #define _XOPEN_SOURCE 500 or similar (please see the man-page linked above for details on this).
I have the following code that is supposed to process ever wile with a .NEF extension.
#include <iostream>
#include <regex>
#include <pthread.h>
#include <dirent.h>
using namespace std;
void *workHorse(void*);
int main (int argc, char *argv[]){
pthread_t t1;
int rc, pos1;
DIR *dir;
struct dirent *ent;
regex e("(.*)(\\.)(NEF|nef)");
if ((dir = opendir (".")) != NULL) {
string fn1;
while ((ent = readdir (dir))!=NULL){
fn1.assign(ent->d_name);
if (regex_match ( fn1, e )){
cout<<"F :"<<fn1.c_str()<<" "<<endl;
if (rc=pthread_create( &t1, NULL, &workHorse, (void*)&fn1)){
cout<<"Error creating threads "<<rc<<endl;
exit(-1);
}
}
}
}
return 0;
}
void *workHorse(void *fileName){
int ret;
cout<<"W :"<<((string*)fileName)->c_str()<<endl;
pthread_exit(NULL);
}
There is just one file with .NEF extension in the directory. My expected output is -
F :DSC_0838.NEF
W :DSC_0838.NEF
However, I get
F :DSC_0838.NEF
W :RGBbmp.bmp
RGBbmp.bmp is another file in the same directory. What is wrong with my code? Why does it not work as expected?
The above code was compiled using -
g++ tmp.cpp -pthread --std=c++11
fn1's address is shared between the main thread and the secondary p_thread you create.
While the new thread is bootstrapping, the main thread changes the value in 'fn1' memory address, and the secondary thread reads the name of a different file (because in the main thread fn1 now has a new value).
You need to create a copy of the string you pass to the secondary thread, or you need to syncrhonize your read/write, I would recommend the former since it is way easier.
In this line:
if (rc=pthread_create( &t1, NULL, &workHorse, (void*)&fn1))
You are passing the address of fn1, the value then is changed in the main loop to some other file names, and by the time the tread comes up, it is now in RGBbmp.bmp
I looked around and I couldn't find the answer to how exactly to do this. I am trying to use Pantheios for logging and I want to write to an external file (otherwise whats the point). I am following one of the examples provided but It doesn't seem to be making the log file anywhere. Here is the code:
Edit: Also pantheios_be_file_setFilePath is returning -4 (PANTHEIOS_INIT_RC_UNSPECIFIED_FAILURE) so thats.....not helpful
#include "stdafx.h"
#include <pantheios/pantheios.hpp>
#include <pantheios/implicit_link/core.h>
#include <pantheios/implicit_link/fe.simple.h>
#include <pantheios/implicit_link/be.WindowsConsole.h>
#include <pantheios/implicit_link/be.file.h>
#include <pantheios/frontends/fe.simple.h>
#include <pantheios/backends/bec.file.h>
#include <pantheios/inserters/args.hpp>
PANTHEIOS_EXTERN_C const PAN_CHAR_T PANTHEIOS_FE_PROCESS_IDENTITY[] = PANTHEIOS_LITERAL_STRING("LogTest");
int _tmain(int argc, _TCHAR* argv[])
{
try
{
pantheios_be_file_setFilePath(PANTHEIOS_LITERAL_STRING("testlogforme.log"), PANTHEIOS_BE_FILE_F_TRUNCATE, PANTHEIOS_BE_FILE_F_TRUNCATE, PANTHEIOS_BEID_ALL);
pantheios::log(pantheios::debug, "Entering main(", pantheios::args(argc,argv, pantheios::args::arg0FileOnly), ")");
pantheios::log_DEBUG("debug yo");
pantheios::log_INFORMATIONAL("informational fyi");
pantheios::log_NOTICE("notice me!");
pantheios::log_WARNING("warning!!");
pantheios::log_ERROR("error omg");
pantheios::log_CRITICAL("critical!!!");
pantheios::log_ALERT("alert mang");
pantheios::log_EMERGENCY("EMERGENCY!!!!!");
pantheios_be_file_setFilePath(NULL, PANTHEIOS_BEID_ALL);
system("pause");
return EXIT_SUCCESS;
}
catch(std::bad_alloc&)
{
pantheios::log_ALERT("out of memory");
}
catch(std::exception& x)
{
pantheios::log_CRITICAL("Exception: ", x);
}
catch(...)
{
pantheios::puts(pantheios::emergency, "Unexpected unknown error");
}
return EXIT_FAILURE;
}
Maybe I'm not calling a method or maybe its not being saved to a good location?
It turns out that some of the examples out there for pantheios are incorrect. You DO need to call pantheios_init() even if you are in C++. Here Is the example I got to work after deleting all my code and implementing an example that works.
// Headers for main()
#include <pantheios/pantheios.hpp>
#include <pantheios/backends/bec.file.h>
// Headers for implicit linking
#include <pantheios/implicit_link/core.h>
#include <pantheios/implicit_link/fe.simple.h>
#include <pantheios/implicit_link/be.file.h>
PANTHEIOS_EXTERN_C const char PANTHEIOS_FE_PROCESS_IDENTITY[] = "testLOL";
int main()
{
if(pantheios::pantheios_init() < 0)
{
return 1;
}
pantheios::log_NOTICE("log-1"); // save until log file set
pantheios_be_file_setFilePath("mylogfile.log"); // sets log file; write "log-1" stmt
pantheios::log_NOTICE("log-2"); // write "log-2" stmt
pantheios_be_file_setFilePath(NULL); // close "mylogfile"
pantheios::log_NOTICE("log-3"); // save until log file set
pantheios_be_file_setFilePath("mylogfile2.log"); // sets log file; write "log-3" stmt
pantheios::log_NOTICE("log-4"); // write "log-4" stmt
//system("pause");
return 0;
} // closes "mylogfile2" during program closedown
I found the example on a different post on stack overflow but like I said, the built in examples do not work.