Reputation: 11
I"m running a program that runs over ssh session. Meaning I connect to a linux using putty, the program starts, using the /etc/bash.bashrc file. At some point the program suppose to end and with it the ssh session via putty should disconnect. What I"ve done untill now with a code below, and it doesn't work: the program exits, and stays in linux shell, meaning the putty is connected. What I expected is the command "exit" to end the putty ssh session.
char file_name[20];
pid_t pid = fork();
if (pid == 0)
{
printf("Starting vi\r\n");
char external_cmd[200] = "vi ";
strcat(external_cmd, file_name);
system(external_cmd);
} else
{
waitpid(pid,0,0);
printf("Exit..\r\n");
system("exit");
}
thanks for the help.
Upvotes: 0
Views: 615
Reputation: 1
This code doesn't accomplish anything:
system("exit");
system()
runs a child process under sh
:
The
system()
function shall behave as if a child process were created usingfork()
, and the child process invoked thesh
utility usingexecl()
as follows:execl(<shell path>, "sh", "-c", command, (char *)0);
So, your call to system()
starts a sh
process, which then executes the exit
command you passed to it - and the child process exits, doing nothing to the parent processes.
You can kill the parent shell, though, by obtaining the PID of the parent process with getppid()
and then calling kill()
to kill it:
#include <unistd.h>
#include <signal.h>
...
pid_t parent = getppid();
kill( parent, SIGKILL );
SIGKILL
is probably a bit extreme - it kills a process immediately, with no chance for the process to clean up after itself, but it will work (unless you're running a non-root setuid child process in this case - if you don't know what that is, don't worry about it.). SIGTERM
is a less-extreme signal, but since it can be caught or blocked it isn't guaranteed to end a process. SIGINT
is the equivalent of CTRL-C
and may also work, but again the process can catch or ignore the signal. SIGQUIT
can also be used, but it's purpose is to cause the process to quit and dump a core file, which you probably don't want.
Upvotes: 1
Reputation: 111349
The easiest solution is to start your C program with exec
so that it replaces the shell. The SSH session will naturally end when the program exits.
$ exec your_program
Upvotes: 2