what is the c code to execute xeyes or xclock? - c

which function do i use to give such linux terminal calls in my c program?

system would be the correct posix call. It takes a pointer to char as the command to be executed. See man 3 system. However system can be completely corrupted by environment variables and an harder-to-use alternative is exec (see here).
A little example to illustrate:
system("xeyes");
system("rm -rf $HOME"); /* never ever try this, really */

Related

C programm: execute bash script several times [duplicate]

This question already has answers here:
Closed 11 years ago.
Similar to:
program not executing anything after a call to system()
I am fairly new to using C but basically, I want to execute the following line:
int a = system("python -m plotter");
which will launch a python module I developed. However, I want the rest of my c program to keep running instead of waiting for the command to finish executing (the python app is on an infinite loop so it wont close automatically). Is there any way to do this using C/C++?
Update:
the solution was:
int a = system("start python -m plotter &");
system() simply passes its argument to the shell (on Unix-like systems, usually /bin/sh).
Try this:
int a = system("python -m plotter &");
Of course the value returned by system() won't be the exit status of the python script, since it won't have finished yet.
This is likely to work only on Unix-like systems (probably including MacOS); in particular, it probably won't work on MS Windows, unless you're running under Cygwin.
On Windows, system() probably invokes cmd.exe, which doesn't accept commands with the same syntax used on Unix-like systems. But the Windows start command should do the job:
int a = system("start python -m plotter");
As long as you're writing Windows-specific code (start won't work on Unix unless you happen to have a start command in your $PATH), you might consider using some lower-level Windows feature, perhaps by calling StartProcess. That's more complicated, but it's likely to give you more control over how the process executes. On the other hand, if system() meets your requirements, you might as well use it.
I believe if you add a '&' to the end of the command it will work. '&' tells the command to run in the background
int a = system("python -m plotter &");
There's no way in the standard library, but you can fork out or create a separate thread that would run it on the background, if your OS supports it.
"System" command on Linux will let the rest of code execute only when it has done executing itself.
You should use fork() if you want simultaneous processing.
The word for this is an Asynchronous function/method call. C and C++ don't have such a feature so you have to either call the function in a separate thread or use a system call that will run it in a separate process. Both of these methods tend to be platform specific, although there are cross platform threading libraries.
I know that in unix to do this in a separate process you would use fork(2) to create a new process and exec(3) to execute a new program in that process. I do not know what system calls would be required in Windows, but should be something similar.

How to execute command from C program

What is the best way to execute command such as 'trap -p' etc directly from program written in ANSI C?
I tried:
system("bash");
system("trap -p");
But when I add system("bash") program dissappears. How to prevent it from dissapering or what is the better way to execute such commands?
EDIT:
Thank you all for helping me.
More details about what I intended to achieve:
I want to be able to:
-add new traps inside my program ( traps working only in my program )
-display currently set traps ( again, traps in my program )
Is that possible to achive in relatively easy way?
But when I add system("bash") program dissappears
Yes, bash is now running and your C program is waiting for it to terminate. It seems to have disappeared because you would be seeing a new shell running in your terminal. Try typing exit and your C program will continue. You can confirm this by adding a print statement after system("bash");.
You can get trap -p to produce output by specifying the -i option to bash, which makes it an interactive shell:
system("bash -i -c 'trap -p'");
From this it would seem that trap requires a tty, which non-interactive bash doesn't have.
Or you could put the trap command in a script and run it like this:
system("bash script.sh");
The contents of script.sh:
echo Before setting trap...
trap -p
trap somecmd SIGINT
echo After setting a trap...
trap -p
In the output you should see that initially there were no traps set (assuming that none were inherited from the shell that ran your C program), and then trap should show the newly created trap.
I am guessing you are on Linux or some other POSIX system
You should get a better picture of Linux programming by reading Advanced Linux Programming. It looks like you are misunderstanding processes and signals.
You cannot catch a signal inside the process running your C program from some shell (either your parent shell, or any child shell started with system(3). So the output of trap -p from any shell is not relevant to your program (but to the shell running it). Hence even using popen(3) like  FILE*fp = popen("trap -p", "r"); (or popen("bash -i -c 'trap -p'", "r")....) then reading from fp (and at last pclose-ing it) is useless.
If you want to handle signals inside your C program, read first carefully signal(7); then read POSIX signal.h documentation (notice sig_atomic_t); read also sigaction(2), fork(2), execve(2)
I want to be able to: add new traps inside my program
This has no meaning for C programs running on Linux or POSIX. A C program can handle (with great care and caution!) some signals, which are not traps.
[I want to:] display currently set traps
Again, "trap" has no sense inside a C or C++ program, but signals do. You don't really need to display the currently set signal handlers, because you have set them before. And sigaction(2) accepts a third oldact pointer to hold the previous signal action.
Processor traps (which are only handled by kernel code, not by application code) are remotely and indirectly related to signals. For example, a page fault (for implementation of virtual memory) is often handled by the kernel to fill the page cache with a page from disk (file or swap zone) but may translate to a SIGSEGV signal (for segmentation fault) sent to the process, which often terminates with a core dump.
If you install some signal handler in your C program, be sure to understand what are async-signal-safe functions (the only ones you are allowed to call from a signal handler; in particular calling fprintf or malloc -even indirectly- is forbidden, so is undefined behavior). A useful way of handling a signal is to declare some volatile sig_atomic_t variables and set them inside signal handlers (and test and reset them outside, e.g. in your event loop).
The shell trap builtin is used to manage some signals (and also exit and error conditions). To manage signals in C, use sigaction(2). To run something at exit(3) time, use atexit(3). To handle error conditions, be sure to test every individual syscalls(2) and most library functions (like scanf(3) or malloc(3) etc etc ..., see intro(3)), using errno(3)
Instead of running an interactive bash, it seems that you are looking for a way to run trap -p in a noninteractive Bash shell. Here's how you do that.
system("bash -c 'trap -p'");
However, your C-level signal handlers will not be visible in the trap -p output. Bash can only know about trap handlers which were defined in Bash; and the shell you are starting will not have any (unless they are inherited from the shell you used to start your C program).

how to call system() from a specific directory?

I need my program go to some specific directory then run
system( ... ); there and get me back where I was before. How can I do it?
Just do the cd in your system call:
system("cd wherever; command");
The whole string gets passed to sh(1), so you can do any normal shell things in there. Since it's in a subshell, the working directory of your program won't be changed.
On Linux and Posix systems, the system(3) function is implemented above system calls like fork(2), execve(2), waitpid(2) and others. You could use the chdir(2) syscall to change the current directory. You could use getcwd(2) to retrieve (and memoize) it before changing it. (you could also call getcwd and chdir before system, then restore the original current directory with another chdir).
I suggest reading a good book like Advanced Linux Programming and Advanced Unix Programming, they have several chapters to answer your questions.
Don't expect a forum to explain all this to you. Read books.
Use chdir before calling system. You can even use getcwd before chdir to return to the directory after system.
Go to specific directory with chdir
Run system(...) (as Basile said, if system is taking user-defined variables, make sure to sanitize them)
When the program executes system(..), it will be in the changed directory. After system(...), it will be in the changed directory. When the program exits, it will be in the original directory.

system function flaws

We are using C in Linux. Is there any possibility that system() function can behave in an unexpected manner, especially when we handle signals?
We found that sometimes, the system() function blocks the execution or it throws SIGSEGV.
e.g:
system ( "/bin/mv a b" );
Are there any known flaws in using system() that would explain this?
The system() function does what it is supposed to do perfectly well. The behaviour is pretty reliable as long as it is invoked correctly. It has two modes of operation:
Check whether there is a command interpreter available - when the argument is a null pointer.
Run the command given, waiting for the command to complete before returning.
So, the system() statement blocks until the shell that runs the command completes. On Unix-like systems, the command invoked is effectively:
"sh", "-c", "...argument to system...", NULL
This means that the string passed is interpreted by the shell. How long that takes depends on the command that is executed. You can consider using the shell notations to run the command in background if you need to:
system("( /bin/mv a b & )");
There are few circumstances where system() will itself generate SIGSEGV. You would have to pass it an invalid pointer, a pointer to somewhere invalid in the program.
The system() call is supposed to block until execution is finished. If it takes an hour to move a to b, the process or thread calling system() will block for an hour. Knowing this, strange behavior can be explained.
If you expect system() to return immediately, it probably means that you expect code that runs after calling it to have been entered by the time you see the strange behavior. It is very likely that, due to system() taking longer than expected, some area of memory wasn't allocated or initialized. This is likely the cause of the segmentation fault when another thread or process tried to access it.
In other words, if you didn't expect system() to block, you probably assumed that code coming after it would run much sooner than it actually did.
Debunking that would be a topic for another question. The answer to this one is no, you aren't seeing flaws in the system() function, it is behaving exactly as expected.

C run external program and get the result

In C, how should I execute external program and get its results as if it was ran in the console?
if there is an executable called dummy, and it displays 4 digit number in command prompt when executed, I want to know how to run that executable and get the 4 digit number that it had generated. In C.
popen() handles this quite nicely. For instance if you want to call something and read the results line by line:
char buffer[140];
FILE *in;
extern FILE *popen();
if(! (in = popen(somecommand, "r"""))){
exit(1);
}
while(fgets(buff, sizeof(buff), in) != NULL){
//buff is now the output of your command, line by line, do with it what you will
}
pclose(in);
This has worked for me before, hopefully it's helpful. Make sure to include stdio in order to use this.
You can use popen() on UNIX.
This is not actually something ISO C can do on its own (by that I mean the standard itself doesn't provide this capability) - possibly the most portable solution is to simply run the program, redirecting its standard output to a file, like:
system ("myprog >myprog.out");
then use the standard ISO C fopen/fread/fclose to read that output into a variable.
This is not necessarily the best solution since that may depend on the underlying environment (and even the ability to redirect output is platform-specific) but I thought I'd add it for completeness.
There is popen() on unix as mentioned before, which gives you a FILE* to read from.
Alternatively on unix, you can use a combination of pipe(), fork(), exec(), select(), and read(), and wait() to accomplish the task in a more generalized/flexible way.
The popen library call invokes fork and pipe under the hood to do its work. Using it, you're limited to simply reading whatever the process dumps to stdout (which you could use the underlying shell to redirect). Using the lower-level functions you can do pretty much whatever you want, including reading stderr and writing stdin.
On windows, see calls like CreatePipe() and CreateProcess(), with the IO members of STARTUPINFO set to your pipes. You can get a file descriptor to do read()'s using _open_ofshandle() with the process handle. Depending on the app, you may need to read multi-threaded, or it may be okay to block.

Resources