Turbo C++ system function running an executable - c++

How to run any exe file from turbo c++? I know that I should stop using turbo c++ and move one to Dev or Code::Blocks, but my school doesn't agree so I gotta wing it.
I just want to know how to run a file with or without the system() function.
Any kind of advice is welcome
Here's what I have tried so far:
1
#include<process.h>
int main()
{
system("tnfsv13.exe"); //tnfsv being a 16-bit application(The need for slowness v 13)
return 0;
}
2
#include<process.h>
int main()
{
system("tnfsv13.bat");
return 0;
}
tnfsv13.bat:
start "c:\TurboC3\BIN\" tnfsv13.exe
NOTE: Just a doubt, you guys: system() is not working in windows XP. I tried it using dosbox in windows 7 and it works well, but in XP it does absolutely nothing. Not even the system("dir") command seems to work but system(NULL) returns 1. Any guesses why?
Thanks.

You can also use Turbo C++'s execl() function. execl() loads and runs C:\\TC\\BIN\\tnfsv13.exe. NULL means there are no arguments to send to tnfsv13.exe. If an error occurs, execl() returns -1 into int c .
#include<stdio.h>
#include<process.h>
int main()
{
int c = execl("C:\\TC\\BIN\\tnfsv13.exe", NULL);
return 0;
}
Explanation:
execl() loads and executes a new child process. Because the child
process is placed in the memory currently occupied by the calling
process, there must be sufficient memory to load and execute it.
'pathname' specifies the file name of the child process. If
'pathname' has a file name extension, then only that file is searched
for. If 'pathname' ends with a period (.), then 'pathname' without an
extension is searched for. If that filename is not found, then
".EXE" is appended and execl() searches again. If 'pathname' has no
extension and does not end with a period, then execl() searches for
'pathname' and, if it is not found, appends ".COM" and searches
again. If that is not found, it appends ".EXE" and searches again.
'arg0', 'arg1',...'argn' are passed to the child process as command-
line parameters. A NULL pointer must follow 'argn' to terminate the
list of arguments. 'arg0' must not be NULL, and is usually set to
'pathname'.
The combined length of all the strings forming the argument list
passed to the child process must not exceed 128 bytes. This includes
"n" (for 0-n arguments) space characters (required to separate the
arguments) but does not include the null ('\0') terminating
character.
Returns: If execl() is successful, it does not return to the
calling process. (See the spawn...() routines for a
similar function that can return to the calling
process). If an error occurs, execl() returns -1 to
the calling process. On error, 'errno' (defined in
<errno.h>) is set to one of the following values
(defined in <errno.h>):
E2BIG Argument list or environment list too big.
(List > 128 bytes, or environment > 32k)
EACCES Locking or sharing violation on file.
(MS-DOS 3.0 and later)
EMFILE Too many files open.
ENOENT File or path not found.
ENOEXEC File not executable.
ENOMEM Not enough memory.
Notes: Any file open when an exec call is made remains open
in the child process. This includes
'stdin','stdout', 'stderr', 'stdaux', and 'stdprn'.
The child process acquires the environment of the
calling process.
execl() does not preserve the translation modes of
open files. Use setmode() in the child process to
set the desired translation modes.
See the spawn...() routines for similar though more
flexible functions that can return to the calling
program.
Caution: The file pointers to open buffered files are not
always preserved correctly. The information in the
buffer may be lost.
Signal settings are not preserved. They are reset to
the default in the child process.
-------------------------------- Example ---------------------------------
The following statements transfer execution to the child process
"child.exe" and pass it the three arguments "child", "arg1",
and"arg2":
#include <process.h> /* for 'execl' */
#include <stdio.h> /* for 'printf' and 'NULL' */
#include <errno.h> /* for 'errno', 'ENOENT' and 'ENOMEM' */
main()
{
execl("child.exe", "child", "arg1", "arg2", NULL);
/* only get here on an exec error */
if (errno == ENOENT)
printf("child.exe not found in current directory\n");
else if (errno == ENOMEM)
printf("not enough memory to execute child.exe\n");
else
printf(" error #%d trying to exec child.exe\n", errno);
}

system() works fine, though it may not work exactly the way you expect: it does the same thing as typing a command at a MSDOS (or Win32) command prompt including input and output being connected to the console.
If you just want to run a program, pass parameters, and not return from it, use a convenient form from the exec() family of functions. See this for one example.

Related

running multiple execve functions in one c++ file

I have to write a c++ program which "counts the number of lines, words and the number of bytes from a text file", all of which must be in a new line.
I have to use the wc command in my c++ program. I have managed to get the number of lines:
char *envp[] = {NULL};
char *command[] = {"wc", "-l", filename.c_str(), NULL};
execve("/usr/bin/wc", command, envp);
After the above statements, I have one which replaces "-l" with "-w" and so forth. But my program ends immediately after the first execve() statement.
How do I get all my statements to execute even after the execve() statement?
N.B: This will be my first time running system commands using a c++ program.
Thank you in advance.
execve replaces current executable image with a specified one and therefore never returns upon success. If you want to continue executing main program then you will need to fork first. Or use something as dull as system function.

Are ALL system() calls a security risk in c++?

A post in this (Are system() calls evil?) thread says:
Your program's privileges are inherited by its spawned programs. If your application ever runs as a privileged user, all someone has to do is put their own program with the name of the thing you shell out too, and then can execute arbitrary code (this implies you should never run a program that uses system as root or setuid root).
But system("PAUSE") and system("CLS") shell to the OS, so how could a hacker possibly intervene if it ONLY shells to a specific secure location on the hard-drive?
Does explicitly flush—by using fflush or _flushall—or closing any stream before calling system eliminate all risk?
The system function passes command to the command interpreter, which executes the string as an operating-system command. system uses the COMSPEC and PATH environment variables to locate the command-interpreter file CMD.exe. If command is NULL, the function just checks whether the command interpreter exists.
You must explicitly flush—by using fflush or _flushall—or close any stream before you call system.
https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/system-wsystem
In case, there are any doubts here's the actual snippet from the MS' implementation (very simple and straightforward):
// omitted for brevity
argv[1] = _T("/c");
argv[2] = (_TSCHAR *) command;
argv[3] = NULL;
/* If there is a COMSPEC defined, try spawning the shell */
/* Do not try to spawn the null string */
if (argv[0])
{
// calls spawnve on value of COMSPEC vairable, if present
// omitted for brevity
}
/* No COMSPEC so set argv[0] to what COMSPEC should be. */
argv[0] = _T("cmd.exe");
/* Let the _spawnvpe routine do the path search and spawn. */
retval = (int)_tspawnvpe(_P_WAIT,argv[0],argv,NULL);
// clean-up part omitted
As to concerns of what _tspawnvpe may actually be doing, the answer is: nothing magical. The exact invocation sequence for spawnvpe and friends goes as following (as anybody with licensed version of MSVC can easily learn by inspecting the spanwnvpe.c source file):
Do some sanity checks on parameters
Try to invoke _tspawnve on the passed file name. spawnve will succeed if the file name represents an absolute path to an executable or a valid path relative to the current working directory. No further checks are done - so yes, if a file named cmd.exe exists in current directory it will be invoked first in the context of system() call discussed.
In a loop: obtain the next path element using `_getpath()
Append the file name to the path element
Pass the resulted path to spwanvpe, check if it was successful
That's it. No special tricks/checks involved.
The original question references POSIX not windows. Here there is no COMSPEC (there is SHELL but system() deliberately does not use it); however /bin/sh is completely, utterly vulnerable.
Suppose /opt/vuln/program does system("/bin/ls"); Looks completely harmless, right? Nope!
$ PATH=. IFS='/ ' /opt/vuln/program
This runs the program called bin in the current directory. Oops. Defending against this kind of thing is so difficult it should be left to the extreme experts, like the guys who wrote sudo. Sanitizing environment is extremely hard.
So you might be thinking what is that system() api for. I don't actually know why it was created, but if you wanted to do a feature like ftp has where !command is executed locally in the shell you could do ... else if (terminalline[0] == '!') system(terminalline+1); else ... Since it's going to be completely insecure anyway there's no point in making it secure. Of course a truly modern use case wouldn't do it that way because system() doesn't look at $SHELL but oh well.

Why this line wouldn't be printed? (C++ threads)

Found this example in the net and can't find out why this line wouldn't be printed
#include<stdlib.h>
#include<unistd.h>
int main()
{
pid_t return_value;
printf("Forking process\n");
return_value=fork();
printf("The process id is %d
and return value is %d\n",
getpid(), return_value);
execl("/bin/ls/","ls","-l",NULL);
printf("This line is not printed\n");
}
A successful execl never returns, see the man page:
The exec() functions only return if an error has occurred.
Instead, the host process is replaced by what you are execing, in this case, the ls process image:
The exec() family of functions replaces the current process image with a new process image.
This way, your program will be replaced in memory before reaching the last printf statement, causing it to never execute.
exec*() functions is a special in sense that they are non-returning. Typical implementation of that function "replaces" modules of current process that is effectively the same as starting of new program right inside of current process. In your case new program is /bin/ls. During execl() all previous images are unloaded from process, then /bin/ls and all its dependencies are loaded and control is passed to entry point of /bin/ls, that calls its main() function, so on.
Thus there is no place to return control after execl() since module that calls it no more exists in address space of current process.

pidof from a background script for another background process

I wrote a c++ program to check if a process is running or not . this process is independently launched at background . my program works fine when I run it on foreground but when I time schedule it, it do not work .
int PID= ReadCommanOutput("pidof /root/test/testProg1"); /// also tested with pidof -m
I made a script in /etc/cron.d/myscript to time schedule it as follows :-
45 15 * * * root /root/ProgramMonitor/./testBkg > /root/ProgramMonitor/OutPut.txt
what could be the reason for this ?
string ReadCommanOutput(string command)
{
string output="";
int its=system((command+" > /root/ProgramMonitor/macinfo.txt").c_str());
if(its==0)
{
ifstream reader1("/root/ProgramMonitor/macinfo.txt",fstream::in);
if(!reader1.fail())
{
while(!reader1.eof())
{
string line;
getline(reader1,line);
if(reader1.fail())// for last read
break;
if(!line.empty())
{
stringstream ss(line.c_str());
ss>>output;
cout<<command<<" output = ["<<output<<"]"<<endl;
break;
}
}
reader1.close();
remove("/root/ProgramMonitor/macinfo.txt");
}
else
cout<<"/root/ProgramMonitor/macinfo.txt not found !"<<endl;
}
else
cout<<"ERROR: code = "<<its<<endl;
return output;
}
its output coming as "ERROR: code = 256"
thanks in advacee .
If you really wanted to pipe(2), fork(2), execve(2) then read the output of a pidof command, you should at least use popen(3) since ReadCommandOutput is not in the Posix API; at the very least
pid_t thepid = 0;
FILE* fpidof = popen("pidof /root/test/testProg1");
if (fpidof) {
int p=0;
if (fscanf(fpidof, "%d", &p)>0 && p>0)
thepid = (pid_t)p;
pclose(fpidof);
}
BTW, you did not specify what should happen if several processes (or none) are running the testProg1....; you also need to check the result of pclose
But you don't need to; actually you'll want to build, perhaps using snprintf, the pidof command (and you should be scared of code injection into that command, so quote arguments appropriately). You could simply find your command by accessing the proc(5) file system: you would opendir(3) on "/proc/", then loop on readdir(3) and for every entry which has a numerical name like 1234 (starts with a digit) readlink(2) its exe entry like e.g. /proc/1234/exe ...). Don't forget the closedir and test every syscall.
Please read Advanced Linux Programming
Notice that libraries like Poco or toolkits like Qt (which has a layer QCore without any GUI, and providing QProcess ....) could be useful to you.
As to why your pidof is failing, we can't guess (perhaps a permission issue, or perhaps there is no more any process like you want). Try to run it as root in another terminal at least. Test its exit code, and display both its stdout & stderr at least for debugging purposes.
Also, a better way (assuming that testProg1 is some kind of a server application, to be run in at most one single process) might be to define different conventions. Your testProg1 might start by writing its own pid into /var/run/testProg1.pid and your current application might then read the pid from that file and check, with kill(2) and a 0 signal number, that the process is still existing.
BTW, you could also improve your crontab(5) entry. You could make it run some shell script which uses logger(1) and (for debugging) runs pidof with its output redirected elsewhere. You might also read the mail perhaps sent to root by cron.
Finally I solved this problem by using su command
I have used
ReadCommanOutput("su -c 'pidof /root/test/testProg1' - root");
insteadof
ReadCommanOutput("pidof /root/test/testProg1");

started from command line?

I have a simple C/CPP process running on a linux system. This is a.out.
Another process is capable to start a.out inside its code. This is b.out.
What code do I need inside a.out to understand that it is executed from the command line?
Eg ./a.out
Is there a way a process to know if it started from the cmd or started from another process?
You can't find out in general whether a program was started "from the command line" (by a user's explicit command), but you can find out whether its standard input and output are talking to a terminal/command window:
#include <unistd.h>
isatty(fileno(stdin))
and stdout return whether standard input/standard output are terminals.
If you need to know what process starting your program, use the getppid system call to get the parent's process ID (ppid), then read the pseudo-file /proc/ppid/cmdline.
You can check its parent task ID, using getppid()
You can do multiple things, but none will be 100% reliable:
isatty(0) to check whether standard input is a TTY terminal,
check for the parent task ID (getppid()), then lookup the parent's PID to match it against its executable's path (using whatever you want. a call to ps and some parsing could do, or have fun using /proc/)
you could also just have a look at the environment variables set up. do a printout of all the values contained in the env. To do that, either use the extern environ variable:
extern char **environ;
or modify your main() prototype to be:
int main(int ac, char **av, char **environ)
I would set an environment variable, in the parent process, to some value (say the parent pid), and have the child process check for it.
It is unlikely that a shell user would set this variable (call it something unlikely to name-clash), so if this variable is set to the expected value, then you know that it is being started from the parent process.
You can check whether its standard input is a terminal:
if(isatty(0)) { ... }
In short: you can't doing it directly.
In long: look you can check the getppid() value and compare it with the bash PID orb.out PID
TO search for a process inside the process table with Known PID with C you can do this:
1) get the PPID of a.out and search with this value in /porc and then if you find the folder check the cmdline file and check if this process is b.out or shell process.
2) you can deal with sysctl system call and dealing with kernel param's(you can google it)
3)
pid_t ppid = getppid();
system("pidof bash > text.in");
the system will get the pid of any shell process and write the result to text.in file
it contains all bash PID's space separated you can compare this values with getppid() value.
Good Luck.