I am using a system() to call an executable program(A server) . Now after a certain time I want to terminate this program from my c program itself. Does anyone know how to do this?
OS running:(http://rcn-ee.net/deb/rootfs/precise/ubuntu-12.04-r4-minimal-armhf-2012-07-16.tar.xz)
The best way to do this is to use a function that gives you more control over the resulting process than system() does. However, this would be platform specific.
For Windows, use CreateProcess() which returns a HANDLE which you can use later in TerminateProcess() to kill the process.
For Unix, use fork() and exec() which gives you the pid of the child process, which you can use later in kill() to kill the process.
Related
I want to execute to different network commands which show same output by assigning them to two different threads, they should execute in parallel and using c++
There is no point using threads for this problem, because the only way to execute an external utility ("linux system command") is to fork() a child process and then exec() the utility.
Since you cannot exec() inside a thread -- it would replace the entire process, not just the thread in which it is called -- you might as well just go with the flow and use multiple processes.
You can create as many child processes as you like (within reason) and exec() a different external command in each one. The various processes will run independently.
You can execute inside a thread, if this is on unix which I am assuming you can make a function, call pthread_create and pass it that function. Inside that function just do a system_call. Then do pthread_join on the thread ids pthread_create returns, and wait for it to return. Then you know its done executing, and can exit, or go on with your program. Similar things will work on windows as well.
How can I terminate my program (using code) immediately.
I don't want destructors called.
I don't want any hooks to execute.
I just want the bare minimum way to kill the program.
(I'm not looking for answers that say this is not kosher. I know it's not.)
EDIT: Looking for Windows and Linux solutions.
EDIT2: I've tried exit, _exit, abort, and terminate without success on Windows.
EDIT3: While I don't yet have access to a Linux box, I was able to successfully kill my Windows program with the following code:
int pid = _getpid();
char buff[256];
sprintf(buff, "taskkill /pid %d /f", pid);
system(buff);
Just call _exit(), available on both Linux and Windows. It won't produce a core-dump like abort() will.
Edit: If _exit() isn't good enough for you, you'll probably have to go platform-specific.
On Windows, you can call TerminateProcess(), which is, as far as I know, the most forceful/immediate method to kill a process exposed by the Windows API (though if there's a more forceful one I'd love to learn about it).
On Linux, raising SIGKILL might be better, as suggested by Jeffery Thomas. I actually don't know if SIGKILL is more forceful/immediate than _exit() or not.
Both of these methods are asynchronous.
On POSIX compliant UNIX systems, raise(SIGKILL) will do what you want.
For Windows, TerminateProcess(GetCurrentProcess(),0) is what I would look at first. NOTE: This could cause problems for globally shared DLL's.
As a final comment, you didn't give any details, but for whatever you are trying to do, you're doing it the wrong way if this is your way out.
Use _exit(). This will kill your program immediatly.
Try calling the abort() function in C, or std::terminate in C++.
(terminate is also a C function in Visual C++, but it's nonstandard.)
In C++11 _Exit (note: uppercase E) is specified as §18.5/3
” The program is terminated without executing destructors for objects of automatic, thread, or
static storage duration and without calling functions passed to atexit()
If you want possible handlers to execute then you can instead call std::quick_exit, which calls registered handlers and then _Exit.
There appear to be two common ways of running an external executable from C in unix, the
system()
call and
pid = fork()
switch(pid)
//switch statement based on return value of pid,
//one branch of which will include and exec() command
Is there any reason to prefer a fork/exec over system in the case where they are functionally equivalent (parent process waits for child to finish, no complex information is returned from child)?.
system executes a command-interpreter, i.e. a shell, which (a) is slower than a direct fork/exec, (b) may behave differently on different systems and (c) is a potential security hazard if you pass it a string from an untrusted source. Also, system waits for the child process to exit, while you might want it to run concurrently with the parent process.
More in general, the low-level fork/exec gives you additional control: before or in between the two operations, you might want to chdir, open pipes, close file descriptors, set up shared memory, etc.
(By different systems, I don't mean Windows vs. Unix (as Windows doesn't even have fork): I'm talking Red Hat Linux vs. Ubuntu. The former uses Bash to execute what is passed to system, the latter a lightweight POSIX-compatible shell.)
fork() creates a new process. If you don't need to do that, just use system() (or popen()). You might want a second process to achieve parallelism, or for finer-grained control over the job, but often you just don't care for that if the job is meant to be synchronous.
On the other hand, I find that 95% of uses of system() are unnecessary or would somehow be better off done another way (e.g. using zlib instead of system("gzip")). So maybe the best answer is to use neither!
Going via system() additionally invokes a shell process, which might not be what you want.
Also the calling process is notified only when such shell dies not when the actual process run by the shell died.
system() will type out the command and execute it like a user would have typed out.
i mostly saw it like system("pause"); system("cls");
But if you need to control the child process, you want to fork.
I'm writing a program (A genetic algorithm implementation) which executes another program using "system" method to calculate fitness. The problem is that another program sometimes hangs for unlimited amount of time. How can I execute a program with some time limit from C++.
Both POSIX and c++ solutions are appreciated. And more or less this will be run once application so solution doesn't have to be very elegant.
I'm running Linux CentOS distribution and am testing on Cygwin. For compiler I use gcc 4.1.2 with boost library.
Any help is apreciated
Instead of system, execute the program with the fork/exec idiom. Before the exec, set RLIMIT_CPU to a maximum value with setrlimit in the child.
Make sure the child does not ignore SIGXCPU (which is very unlikely).
You could create a timer (with boost timer for example) and then try to kill the child process... this assume that you use fork and exec to launch all your child, and you stored each pid.
If this 'another' program is yours or you have sources under public license it's better probably to make it not a separate program but a separate thread in the main program. In this case you can easily control it.
If this 'another' program is yours or you have sources under public license but don't want (or can't) follow the suggestion above may be it is easier to fix the program to prevent hanging.
Shitty method:
do fork(), remeber PID, call exec*("my-prog", ...)
create thread in the main program with timer.
when time fires kill the process using kill() and PID remembered.
Is there any way I can have a thread branch off into its own independent process? I know there's the CreateProcess function but as far as I can tell, you can only run external applications with it. Is what I'm asking for at all possible?
It is possible.
You could call CreateProcess with a dummy application and with the CREATE_SUSPENDED flag so it doesn't run immediately. Then you can use VirtualAllocEx to allocate memory space in the created process and WriteProcessMemory to write code and data into it. And then unsuspend the process to run it.
You can also use CreateRemoteThread to create a process running within the context of another existing process.
So what you want to do is possible, but it's really not a simple thing to do in a windows environment so you'd have to have a really good reason to want to do it.
That's not possible under Windows. On Posix platforms the desired effect could be achieved by fork()ing.