How to use command in function system() [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I wanted to use the system("cd \") function to go to the root directory but it does not work because as I want to create a folder system("md examplecpp"); in this path, a folder is created where I have a program.

Your problem, is that "the current directory" is a per-process property (although a child process inherits the current directory of its parent as an initial setting). The system function creates a shell process, which executes the cd command (thus changing the current directory of the shell process), and then exits. The current directory of the parent process (your program) is never changed.
Look into the _chdir function (or for Posix chdir)
Edit: You are definitely on Windows - you even put it in the tags!

I wanted to use the system("cd \") function to go to the root
directory but it does not work because as I want to create a folder
system("md examplecpp");
Merge the two (or more) commands together into one command, separated by semicolon, prior to invoking system.
i.e.
std::string cmd = "cd /home/dmoen ; mkdir examplecpp ; ls -lsa ";
std::cout << "\nsystem command: " << cmd << "\n" << std::endl;
std::system (cmd.c_str());
Lesson - the cmd string should look just like you'd type at a command prompt. During testing, you might decide to include a "rmdir examplecpp", as "mkdir" complains if dir already exists.
output (with uninteresting things snipped):
system command: cd /home/dmoen ; mkdir examplecpp ; ls -lsa
total 402216
4 drwxr-xr-x 105 dmoen dmoen 4096 Dec 23 11:42 .
4 drwxr-xr-x 5 root root 4096 Jan 3 2016 ..
[snip]
4 drwxrwxr-x 2 dmoen dmoen 4096 Dec 23 11:42 examplecpp
[snip]

Related

Calling shell script from system c++ function making the shell script running as different user

I am using the system c++ call to execute the shell script the caller program is running as root but the shell sctipt which is called form the c++ code is running as different user.
How can I make sure the shell script should also run as root user like the c++ binary.
I don't want to rely on using sudo command as it can ask for password.
> [user#user ~]$ ll a.out temp.sh
> -rwsrwsr-x 1 root root 8952 Jun 14 13:16 a.out
> -rwxrwxr-x 1 user user 34 Jun 14 15:43 temp.sh
[user#user ~]$ cat temp.sh
#!/bin/bash read -n 1 -p "Hello"
[user#user ~]$ ps aux | grep temp
root 13247 0.0 0.0 13252 1540 pts/0 S+ 15:44 0:00 ./a.out ./temp.sh
user 13248 0.0 0.0 113152 2544 pts/0 S+ 15:44 0:00 /bin/bash ./temp.sh
c++ code
#include <bits/stdc++.h>
using namespace std;
int main(int argc, char *argv[])
{
system(argv[1]);
return 0;
}
A few bits of documentation to start:
From man 3 system's caveats section:
Do not use system() from a privileged program (a set-user-ID or set-group-ID program, or a program with capabilities) because strange values for some environment variables might be used to subvert system integrity. For example, PATH could be manipulated so that an arbitrary program is executed with privilege. Use the exec(3) family of functions instead, but not execlp(3) or execvp(3) (which also use the PATH environment variable to search for an executable).
system() will not, in fact, work properly from programs with set-user-ID or set-group-ID privileges on systems on which /bin/sh is bash version 2: as a security measure, bash 2 drops privileges on startup. Debian uses a different shell, dash(1), which does not do this when invoked as sh.)
And from the bash manual's description of the -p command line argument (Emphasis added):
Turn on privileged mode. In this mode, the $BASH_ENV and $ENV files are not processed, shell functions are not inherited from the environment, and the SHELLOPTS, BASHOPTS, CDPATH and GLOBIGNORE variables, if they appear in the environment, are ignored. If the shell is started with the effective user (group) id not equal to the real user (group) id, and the -p option is not supplied, these actions are taken and the effective user id is set to the real user id. If the -p option is supplied at startup, the effective user id is not reset. Turning this option off causes the effective user and group ids to be set to the real user and group ids.
So even if your /bin/sh doesn't drop privileges when run, bash will when it's run in turn without explicitly telling it not to.
So one option is to scrap using system(), and do a lower-level fork()/exec() of bash -p your-script-name.
Some other approaches to allowing scripts to run at elevated privileges are mentioned in Allow suid on shell scripts. In particular the answer using setuid() to change the real UID looks like it's worth investigating.
Or configure sudo to not require a password for a particular script for a given user.
Also see Why should I not #include <bits/stdc++.h>?

error while Linking c++ and ns2? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
had done following steps
Download "ex-linkage.cc" file, and save it under the "ns-2" directory.
Open "Makefile", add "ex-linkage.o" at the end of object file list.
Re-compile NS using the "make" command. Download the "ex-linkage.tcl" file
that contains "MyAgent" testing OTcl commands.
Run the OTcl script using command "ns ex-linkage.tcl".
i am getting following error
$ ./ns ex-linkage.tcl
invalid command name "Agent/MyAgentOtcl"
while executing
"Agent/MyAgentOtcl create o3 "
invoked from within
"catch "$className create $o $args" msg"
invoked from within
"if [catch "$className create $o $args" msg] {
if [string match "__FAILED_SHADOW_OBJECT" $msg] {
delete $o
return ""
}
global errorInfo
error "class $..."
(procedure "new" line 3)
invoked from within
"new Agent/MyAgentOtcl"
invoked from within
"set myagent [new Agent/MyAgentOtcl]"
(file "ex-linkage.tcl" line 8
»» invalid command name "Agent/MyAgentOtcl" «« : Looks like you are using an executable 'ns' with no "Linkage".
tar xvf ns-allinone-2.35_gcc482.tar.gz
https://drive.google.com/file/d/0B7S255p3kFXNSGJCZ2YzUGJDVk0/view?usp=sharing
cd ns-allinone-2.35/
patch -p0 < linkage_ns235.patch
https://drive.google.com/file/d/0B7S255p3kFXNYmZ0SWFQaUNhWTA/view?usp=sharing
./install
cd ns-2.35/
sudo make install
cp ns ns235-linkage
sudo cp ns235-linkage /usr/local/bin/
Simulation : ns235-linkage ex-linkage.tcl
.
warning: no class variable Agent/MyAgentOtcl::my_var2_otcl
.
Message From MyPrivFunc
my_var1 = 2
my_var2 = 3.140000
Using the "ns235-linkage" command makes sure you are using the right 'ns'.
P.S. : You are not recompiling with 'make', but with 'make clean && make'. Or by running './install' in the top directory ns-allinone-2.35/.
ns2linkage-ns2
OK, Cygwin. ( Why hide important information http://www.catb.org/~esr/faqs/smart-questions.html ).
The patch command : Install 'patch' , or install the 'Developer tools' if available.
You can use the {ns-2.35/} that comes with ns-allinone-2.35_gcc482.tar.gz ,,, and use the otherwise Cygwin installed {tcl8, tk8, otcl, tclcl}.
Besides that, the patch is just containing the two files ex-linkage.*, and a line for Makefile.in . The patch is supposed to make things easier.
Using : Make a copy of "linkage_ns235.patch" in the folder where you keep ns-2.35/, and do $ patch -p0 < linkage_ns235.patch
cygwin
OK, no working patch function in your cygwin, it seems.
May be your previously setup was OK, and you just have to recompile :
$ cd ns-2.35/ && make clean && make

GDB - unable to get command history working

I'm new to GDB and can't get the command history (auto complete/up arrow to old commands working).
At my root I have a .gbd_init file (and I also have an identical file in my working directory):
set history save
set history filename ~/.gbd_history
set history on
set history expansion on
I also have an empty .gbd_history file at my root.
In GBD 'show history' gives:
(gdb) show history
expansion: History expansion on command input is on.
filename: The filename in which to record the command history is
"/home/jenny/C_Programs/CS575_Algorithms/HW3/Problem1/.gdb_history".
save: Saving of the history record on exit is on.
size: The size of the command history is unlimited.
(gdb)
But the GBD command 'show commands' yields nothing and the up-arrows and tab don't do anything.
The .gbd_history file exists but is empty.
jenny#jennys-virtual-machine ~/C_Programs/CS575_Algorithms/HW3/Problem1 $ ls -ls .gbd*
0 -rwxrwxrwx 1 jenny jenny 0 Oct 1 22:16 .gbd_history
4 -rwxrwxrwx 1 jenny jenny 94 Oct 1 22:01 .gbdinit
What am I missing?
Thanks for any help. Typing in each command is getting old fast.
Jenny
At my root I have a .gbd_init file (and I also have an identical file
in my working directory):
You have misspelled gdb init file name. It should be named .gdbinit. .gbd_init is not get executed by gdb and history saving is not turned on.
Your .gdbinit script obviously is not executed, as you can see from your gdb_history filename, which has it's default value (gdb_history in current directory).
Try executing this init script in your current directory with gdb -x .gdbinit, as it may be disabled by default. At least my gdb wants me to set some kind of auto-load safe-path before it will allow loading of init scripts residing outside of home directory. See details here.
If you are looking to use history only to not have to repeat commands, you should probably just write a script with all those commands, and execute it with gdb -x script etc.
And surely check this SO thread on how to enable command history easily.

Permission denied in Linux [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
I have logged as root on Linux machine. Now trying to execute a binary file test of C++ but it produce an error "Permission denied". While I have given the permission to the binary (test) using chmod +x test.
Thanks
If the file test is located on a separate mount point, and that mount point is mounted with the noexec flag, you will not be able to execute any binaries on it.
From the mount manpages:
noexec Do not allow direct execution of any binaries on the mounted filesystem.
You can see what flags mount points are mounted with using the following command:
mount -l
If the binary test resides in the directory /dir1/dir2, do either of this (using absolute path):
/dir1/dir2/test
or navigate into the directory containing the program and use the ./ prefix (aka relative path)
cd /dir1/dir2
./test
Try the command ls -l /path/to/your/file after chmod +x /path/to/your/file.
After that, check if the executable bits x are present, i.e., look to the first string that will be printed, it should be something similar to -rwxrwxr-x.
If you don't have the three x, you have a problem with chmod. Probably you're not root.
If you have the x but can't execute the program, the problem is
with your call to the program. You should try to cd into the folder
where the program is located and then execute it like
./program_name.
There's a command called "test" that might be in your path before your code is, which is why you'd type "./test" instead of just "test", which will be found in /usr/bin/test, probably. ("which test" to find out on your system)
I don't know why /usr/bin/test would fail with that error, unless your test software takes parameters and you were giving the (on my system) /usr/bin/test a command that it couldn't do.
If it's not called test, and it's not a path issue, could you post some code and build details?

Windows vs. Linux GCC argv[0] value [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Get path of executable
I'm programming on Windows using MinGW, gcc 4.4.3. When I use the main function like this:
int main(int argc, char* argv[]){
cout << "path is " << argv[0] << endl;
}
On Windows I get a full path like this: "C:/dev/stuff/bin/Test". When I run the same application on Linux, however, I get some sort of relative path: "bin/Test". It's breaking my application! Any idea on how to make sure the path is absolute on both systems?
No, there isn't. Under most shells on Linux, argv[0] contains exactly what the user typed to run the binary. This allows binaries to do different things depending on what the user types.
For example, a program with several different command-line commands may install the binary once, and then hard-link the various different commands to the same binary. For example, on my system:
$ ls -l /usr/bin/git*
-rwxr-xr-x 109 root wheel 2500640 16 May 18:44 /usr/bin/git
-rwxr-xr-x 2 root wheel 121453 16 May 18:43 /usr/bin/git-cvsserver
-rwxr-xr-x 109 root wheel 2500640 16 May 18:44 /usr/bin/git-receive-pack
-rwxr-xr-x 2 root wheel 1021264 16 May 18:44 /usr/bin/git-shell
-rwxr-xr-x 109 root wheel 2500640 16 May 18:44 /usr/bin/git-upload-archive
-rwxr-xr-x 2 root wheel 1042560 16 May 18:44 /usr/bin/git-upload-pack
-rwxr-xr-x 1 root wheel 323897 16 May 18:43 /usr/bin/gitk
Notice how some of these files have exactly the same size. More investigation reveals:
$ stat /usr/bin/git
234881026 459240 -rwxr-xr-x 109 root wheel 0 2500640 "Oct 29 08:51:50 2011" "May 16 18:44:05 2011" "Jul 26 20:28:29 2011" "May 16 18:44:05 2011" 4096 4888 0 /usr/bin/git
$ stat /usr/bin/git-receive-pack
234881026 459240 -rwxr-xr-x 109 root wheel 0 2500640 "Oct 29 08:51:50 2011" "May 16 18:44:05 2011" "Jul 26 20:28:29 2011" "May 16 18:44:05 2011" 4096 4888 0 /usr/bin/git-receive-pack
The inode number (459240) is identical and so these are two links to the same file on disk. When run, the binary uses the contents of argv[0] to determine which function to execute. You can see this (sort of) in the code for Git's main().
argv array
argv[0] is a parameter like any others: it can be an arbitrary NUL terminated byte string. It can be the empty string. It is whatever the launching process wants.
By default, the shell with set argv[0] to whatever is used to name the program: a name looked-up in $PATH, a relative or an absolute path. It can be a symbolic link or a regular file.
To invoke a program with some other value, with zsh (dunno with other shells) use:
ARGV0=whatever_you_want some_program arguments
If you really need the path to the executable, you cannot use the command line on Unix.
Linux only
On Linux: /proc/self/exe is a symbolic link to the executable file.
You can readlink it. You can also stat or open it directly.
Renaming and soft link
A normal soft link is a dumb string, and doesn't know what happens to its target (if it exists at all). But the /proc/self/exe soft link is magic.
In case of renaming, the soft-but-magic-link will follow renaming. In case there are several hard links, it will follow the name of the particular hard link that was used. (So different hard links to the same file are not perfectly equivalent under Linux.)
If this hard link is unlinked, I think " (deleted)" is appended to the value of the symbolic link. Note that this is a valid file name, so another unrelated file could have that name.
In any case, the symbolic link is a hard link to the file, so you can stat or open it directly.
I don't think you can count on anything on a network file system if the binary is renamed or unlinked on another system than the one where the executable is launched.
Security considerations
When your program gets to use the /proc/self/exe special file, it is possible for the file used to launch your program to be unlinked or renamed. This should be taken seriously in case the program is privileged (SUID or Set Capabilities): even if the user doesn't have write access to the original "Set Something" binary, he may be able to make a hard link to it if he has write access to a directory on the same file system, so he may be able to change the name if a running privileged binary.
By the time you readlink, the value returned may refer to another file. (Of course, there is always an unavoidable race condition with opening the result of readlink.)
As usual, NFS does not provides all the same guaranties that local file systems have.
There is no way to ensure that argv[0] is an absolute path because it is supposed to be exactly how the user invoked the program. So, if on a Linux command line you invoke your program via ./bin/Test, then argv[0] should be exactly "./bin/Test".
It seems like a bug in MinGW's runtime if when you invoke the program from a command prompt via .\bin\Test, argv[0] is "C:/dev/stuff/bin/Test". With the latest MinGW (gcc version 4.5.2), invoking a binary via .\bin\Test means argv[0] is ".\bin\Test". A Microsoft Visual C++-built binary (cl version 16.00.40219.01) invoked via .\bin\Test also has ".\bin\Test" for argv[0].